【问题标题】:str.replace() bug? javascriptstr.replace() 错误? javascript
【发布时间】: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。通过索引不同的元素得到 tl 并不重要。
  • @Pointy 不,它没有转换为正则表达式。您可以传递正则表达式或字符串,字符串按字面解释。
  • @Barmar 是的,但它或多或少被视为正则表达式,因此“t”与源字符串中的第一个“t”匹配。

标签: javascript string replace


【解决方案1】:

.replace( x, y) 将用 y 替换第一次出现的 x

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2019-09-21
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    相关资源
    最近更新 更多