为什么str.replace不想更改此<>符号?

问题描述 投票:-1回答:2

我需要将>更改为%3E ..,如果>符号被另一个符号更改,则一切正常。我该如何纠正?

<p id="demo">this > and this > symbol should be replaced.</p>

<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
  var str = document.getElementById("demo").innerHTML; 
  var res = str.replace(/>/g, "%3E");
  document.getElementById("demo").innerHTML = res;
}
javascript html str-replace
2个回答
2
投票

您必须在正则表达式中找到&gt;(大于)并用<代替。

Read more here

<p id="demo">this > and this > symbol should be replaced.</p>

<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
  var str = document.getElementById("demo").innerHTML; 
  var res = str.replace(/\&gt\;/g, "\%3E");
  document.getElementById("demo").innerHTML = res;
}
</script>

1
投票

[如果<div>, <span>, or <noembed>节点的子文本节点包含字符(&),(),innerHTML返回这些字符作为HTML实体"&amp;", "&lt;" and "&gt;"分别。使用Node.textContent获取这些文本的原始副本节点的内容。

© www.soinside.com 2019 - 2024. All rights reserved.