Javascript 如何用HTML代码替换所有特殊字符
我想用字符串中的相应字符替换所有字符 我试过这个代码,但它对我不起作用-Javascript 如何用HTML代码替换所有特殊字符,javascript,html,regex,string,Javascript,Html,Regex,String,我想用字符串中的相应字符替换所有字符 我试过这个代码,但它对我不起作用- // theMainString is the string from which I want the characters replaced let theMainString = "<div>Hello World</div>"; let s1, s2; s1 = (theMainString).replace("<", "&l
// 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
重要的是要认识到,除非使用带有g标志的正则表达式,否则replace只查找第一个实例
一种简单的方法是将字符串作为文本插入到临时元素中,然后检索它的innerHTML
通过这种方式,您可以让dom解析器计算出各种字符并返回它们的html实体,而无需自己对它们进行编目
让主字符串=Hello&World;
设span=document.createElement'span';
span.innerText=主字符串;
console.logspan.innerHTML通过您的代码,replace函数只替换第一次出现的内容。如果使用regex,只需添加一个g选项来全局替换模式 让主字符串=你好世界; 设s1,s2; s1=主字符串。替换:/g; console.logs2;强制性的