Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何用HTML代码替换所有特殊字符_Javascript_Html_Regex_String - Fatal编程技术网

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("<", "&lt;");
s2 = s1.replace(">", "&gt;");
console.log(s2);

// Output: "&lt;div&gt;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;强制性的