【问题标题】:How to replace all the special characters with their HTML codes [duplicate]如何用它们的HTML代码替换所有特殊字符[重复]
【发布时间】:2020-08-18 02:07:10
【问题描述】:

我想将字符串中的所有字符“”分别替换为“”。

我尝试了这段代码,但它对我不起作用 -

// theMainString is the string from which I want the characters replaced

let theMainString = "<div>Hello World</div>";
let s1, s2;
s1 = (theMainString).replace("<", "&lt;");
s2 = s1.replace(">", "&gt;");
console.log(s2);

// Output: "&lt;div&gt;Hello World</div>"

Any help would be highly appreciated

【问题讨论】:

标签: javascript html regex string


【解决方案1】:

重要的是要意识到 replace() 只能找到第一个实例,除非您使用带有 g 标志的正则表达式。

一种简单的方法是将字符串作为文本插入到临时元素中,然后检索它的 innerHTML。

这样您就可以让 dom 解析器找出各种字符并返回它们的 html 实体,而无需自己对它们进行编目

let theMainString = "<div>Hello & World</div>";
let span = document.createElement('span');
span.innerText = theMainString;
console.log(span.innerHTML)

【讨论】:

    【解决方案2】:

    通过您的代码,替换功能仅替换第一次出现。如果你使用正则表达式,你可以添加一个 g 选项来全局替换模式。

    let theMainString = "<div>Hello World</div>";
    let s1, s2;
    s1 = (theMainString).replace(/</g, "&lt;");
    s2 = s1.replace(/>/g, "&gt;");
    console.log(s2);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-05
      • 2012-11-06
      • 1970-01-01
      • 2010-12-25
      • 2020-03-15
      • 2019-08-31
      • 2014-12-23
      • 2015-09-12
      相关资源
      最近更新 更多