【发布时间】:2022-11-17 05:30:20
【问题描述】:
const str = 'test'
const newStr = str.replace(str[3],str[3].toUpperCase())
console.log(newStr) // output: 'Test'
const str2 = 'hello'
const newStr2 = str2.replace(str2[3],str2[3].toUpperCase())
console.log(newStr2) // output: 'heLlo'
出了什么问题?
期待结果:'tesT'
期待结果:'helLo'
【问题讨论】:
-
你能解释一下为什么你期待这些结果吗?
-
.replace()的第一个参数被解释为正则表达式.因此它取代了第一的“测试”中的“t”。 -
str.replace()替换字符的第一个匹配项。所以第一个替换第一个t,第二个替换第一个l。通过索引不同的元素得到t或l并不重要。 -
@Pointy 不,它没有转换为正则表达式。您可以传递正则表达式或字符串,字符串按字面解释。
-
@Barmar 是的,但它或多或少被视为正则表达式,因此“t”与源字符串中的第一个“t”匹配。
标签: javascript string replace