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

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

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

'♣️'.length
// 2

请问这是为什么呢?

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

阅读 3.5k
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

后面跟了个不可见字符。

推荐问题