【问题标题】:Search and replace unicode character搜索和替换 unicode 字符
【发布时间】:2013-03-08 05:57:11
【问题描述】:
我正在使用这个search and replace jQuery 脚本。
我试图将每个字符都放在一个跨度中,但它不适用于 unicode 字符。
$("body").children().andSelf().contents().each(function(){
if (this.nodeType == 3) {
var $this = $(this);
$this.replaceWith($this.text().replace(/(\w)/g, "<span>$&</span>"));
}
});
我应该更改节点类型吗?通过什么方式 ?
谢谢
【问题讨论】:
标签:
javascript
jquery
regex
unicode
【解决方案1】:
用“.”替换 \w(仅单词字符) (所有字符)
$("body").children().andSelf().contents().each(function(){
if (this.nodeType == 3) {
var $this = $(this);
$this.replaceWith($this.text().replace(/(.)/g, "<span>$&</span>"));
}
})
【讨论】:
-
这将与 ??? bananas 一起失败。 "?".replace(/(.)/g, "<span>$&</span>") 导致损坏的字符串 "<span>\uD83C</span><span>\uDF4C</span>"。 (它已经被打破了,所以不允许我将整个未转义的内容作为评论发布;我不得不手动编写转义)
【解决方案2】:
匹配“任何字符”的 RegEx 模式是 . 而不是 \w(仅匹配“单词字符”——在大多数 JS 中,字母数字字符和下划线 [a-zA-Z0-9_] 匹配)。注意. 也匹配空格字符。要只匹配和替换非空格字符,可以使用\S。
有关 JS RegEx 语法的完整列表,请参阅the documentation。
要替换任何和所有字符,请将您的正则表达式设为/./g
$("body").children().andSelf().contents().each(function(){
if (this.nodeType == 3) {
var $this = $(this);
$this.replaceWith($this.text().replace(/(.)/g, "<span>$&</span>"));
}
});