正则将空格替换为 之后html上直接用文本展示了,并没有转化为空格?

弑天下
浏览 810回答 2
2回答

跃然一笑

&nbsp; <div id='div'></div>&nbsp; <script>&nbsp; &nbsp; var text = ' This is&nbsp; a&nbsp; &nbsp;dummy&nbsp; &nbsp;text!&nbsp; &nbsp; ';&nbsp; &nbsp; document.getElementById('div').innerText = text.replace(/ /g, '\u00a0');&nbsp; </script>用&nbsp;'&nbsp;'&nbsp;只有设置为&nbsp;innerHTML&nbsp;有效,用&nbsp;'\u00a0'&nbsp;设置&nbsp;textContent,&nbsp;innerHTML,&nbsp;innerText都有效。

千万里不及你

如果是这种场景,为了防xss,建议使用实体和非实体的转化:function htmlEncode(html) {&nbsp; &nbsp; var sub = document.createElement('div');&nbsp; &nbsp; sub.textContent != null ? sub.textContent = html : sub.innerText = html;&nbsp; &nbsp; var output = sub.innerHTML;&nbsp; &nbsp; sub = null;&nbsp; &nbsp; return output;}function htmlDecode(text) {&nbsp; &nbsp; var sub = document.createElement('div');&nbsp; &nbsp; sub.innerHTML = text;&nbsp; &nbsp; var output = sub.textContent || sub.innerText;&nbsp; &nbsp; sub = null;&nbsp; &nbsp; return output;}
打开App,查看更多内容
随时随地看视频慕课网APP