替换">>"在JavaScript中无法正常工作

时间:2018-03-15 22:43:59

标签: javascript

我尝试更换">>"用"你好"。它不会起作用。为什么?任何暗示都是指定的。感谢。

<p id="demo">a string with >> in it.</p>
<button onclick="myFunction()">Replace ">>" with "hello"</button>
<script>
    function myFunction() {
        var str = document.getElementById("demo").innerHTML; 
        var res = str.replace(">>", "hello");
        document.getElementById("demo").innerHTML = res;
    }
</script>

3 个答案:

答案 0 :(得分:2)

您正在获取HTML实体,请改用.textContent

.innerHTML返回浏览器解析的字符串,因此,例如,此字母á将转换为&aacute;。因此,您使用&gt;&gt;获得innerHTML

&#13;
&#13;
<p id="demo">a string with >> in it.</p>
<button onclick="myFunction()">Replace ">>" with "hello"</button>
<script>
    function myFunction() {
        console.log(document.getElementById("demo").innerHTML); // just to illustrate!
        var str = document.getElementById("demo").textContent; 
        var res = str.replace(">>", "hello");
        document.getElementById("demo").textContent = res;
    }
</script>
&#13;
&#13;
&#13;

除了注意

  • 下次开发时,请使用函数addEventListener将事件绑定到元素。
  • 尝试取消重复查找元素,因此必须将此document.getElementById("demo")存储到变量中,以避免在当前DOM中重复搜索。*

&#13;
&#13;
document.querySelector('button').addEventListener('click', myFunction);

function myFunction() {
  var demoElement = document.getElementById("demo");
  console.log(demoElement.innerHTML); // just to illustrate!

  var str = demoElement.textContent;
  var res = str.replace(">>", "hello");
  demoElement.textContent = res;
}
&#13;
<p id="demo">a string with >> in it.</p>
<button>Replace ">>" with "hello"</button>
&#13;
&#13;
&#13;

资源

答案 1 :(得分:2)

问题是您正在设置 .innerHTML ,它将字符串解析为HTML。当然,>在HTML中具有特殊含义。

相反,请使用 .textContent ,它将字符串视为原始文本而不对其进行解析。

function myFunction() {
        var str = document.getElementById("demo").textContent; 
        var res = str.replace(">>", "hello");
        document.getElementById("demo").textContent = res;
}
<p id="demo">a string with >> in it.</p>
<button onclick="myFunction()">Replace ">>" with "hello"</button>

当HTML解析器将字符串视为HTML并在字符串中查找有效的HTML时,它会正确地将其解析为HTML,但如果它找到了无效的迷路<> HTML,它将它们转移到&lt;&gt; HTML entities ,您可以在此处看到:

// With .innerHTML:

  // Valid HTML in the string returns the string and the HTML
  console.log(document.querySelector("div").innerHTML);

  // HTML syntax, but not valid HTML, returns HTML entities
  console.log(document.querySelector("p").innerHTML);


// With .textContent:

  // Valid HTML is not returned - only the text
  console.log(document.querySelector("div").textContent);

  // HTML Syntax, but not valid HTML, returns unaltered string
  console.log(document.querySelector("p").textContent);
h1 { font-size:1.1em; }
<h1>Both of the following will have .innerHTML used on them: </h1>
<div>A string with <span>valid HTML</span> in it.</div>
<p>A string with  >>> HTML syntax <<<, but not valid HTML in it.</p>

答案 2 :(得分:1)

如果您通过.innerHtml阅读字符,则会对字符进行编码。

enter image description here