JS正则中的$1的一个问题

var str = 'this is a test'
console.log(str.replace(/\b(\w)/g, ('$1'+'a').toUpperCase()))
// tAhis iAs aA tAest

为什么输出的不是TAhis IAs AA TAest

str.replace(/b(w)/g, ('$1').toUpperCase()),为什么调用的toUpperCase这个方法无效。

回复
阅读 3.4k
2 个回答

你对于toUpperCase的作用范围理解错了

str.replace(/\b(\w)/g, ('$1'+'a').toUpperCase())

相当于

str.replace(/\b(\w)/g, '$1A')

$1的大写还是$1,你只是把替换规则的字符串大写了,并没有把替换的结果大写
如果需要大写的话,用楼上的方法就可以了
str.replace(/b(w)/g, v => `${v}a`.toUpperCase())

可以这么写

str.replace(/\b(\w)/g, v => `${v}a`.toUpperCase())
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏