【问题标题】: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("<", "<");
s2 = s1.replace(">", ">");
console.log(s2);
// Output: "<div>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, "<");
s2 = s1.replace(/>/g, ">");
console.log(s2);