【问题标题】: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>"));
    }
});

我应该更改节点类型吗?通过什么方式 ?

谢谢

【问题讨论】:

  • “unicode 字符”是什么意思?
  • (注意:andSelf 在 jQuery 版本 1.8 中是 deprecated。您应该改用 addBack,这是等效的,但我想他们更喜欢这个名称。)

标签: 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, "&lt;span&gt;$&amp;&lt;/span&gt;") 导致损坏的字符串 "&lt;span&gt;\uD83C&lt;/span&gt;&lt;span&gt;\uDF4C&lt;/span&gt;"。 (它已经被打破了,所以不允许我将整个未转义的内容作为评论发布;我不得不手动编写转义)
【解决方案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>"));
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 2011-04-23
    • 1970-01-01
    相关资源
    最近更新 更多