`1♣2♣`.replace(new RegExp('♣️', 'gim'), '-') 为什么无效?

`1♣2♣`.replace(new RegExp('♣️', 'gim'), '-')
// ♣2♣

`1♣2♣`.replace(new RegExp('1', 'gim'), '-')
// -♣2♣

'♣️'.length
// 2

请问这是为什么呢?

如何替换 ♣️ 这种特殊符号呢?

阅读 3.4k
3 个回答
// => 1-2-
`1♣2♣`.replace(/[♣️]/g, '-')

你new RegExp 用的梅花和你字符串中的梅花不是同一个梅花。。。

'♣' === '♣️' // false

encodeURIComponent('♣') // "%E2%99%A3"
encodeURIComponent('♣️') // "%E2%99%A3%EF%B8%8F"

`1♣2♣`.replace(new RegExp('♣', 'gim'), '-')
var a = '♣'
console.log(a.charCodeAt(0)) // 9827
console.log(a.charCodeAt(1)) // NaN
var b = '♣️'
console.log(b.charCodeAt(0)) // 9827
console.log(b.charCodeAt(1)) // 65039
"️" === "" // false

后面跟了个不可见字符。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题