字符串替换只替换第一个匹配项,可以'不要让它全球化

String replace replaces only first match, can't make it global

本文关键字:替换 全球化 可以 第一个 字符串      更新时间:2023-09-26

请帮我,因为我不懂编程。我应该怎么做才能使它替换所有字符串匹配?如果我写/http://example.com/ad//g而不是"http://example.com/ad/"它也不能正常运行。

<!DOCTYPE html>
<html>
<body>
<h3>Instert your links</h3>
input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
</textarea>
<button type="button" onclick="myFunction()">Get clean links</button>
<p id="links"></p>
<script>
function myFunction() {
    var x = document.getElementById("myTextarea").value;
    var x = x.replace("http://example.com/ad/", "http://example.com/story/"); 
    var x = x.replace("'n","</br>");
    document.getElementById("links").innerHTML = x;
}
</script>
</body>
</html>

由于不能直接向String.prototype.replace提供全局标志,因此需要将其提供给作为第一个参数传递的RegExp:

x.replace(/'n/g, '</br>')

如果您不关心在替换中使用原始值,则可以继续传递字符串作为第二个参数。

<!DOCTYPE html>
<html>
<body>
<h3>Instert your links</h3>
input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
</textarea>
<button type="button" onclick="myFunction()">Get clean links</button>
<p id="links"></p>
<script>
function myFunction() {
    var x = document.getElementById("myTextarea").value;
    var x = x.replace(/http:'/'/example.com'/ad'//g, "http://example./com/story/"); 
    var x = x.replace(/'n/g,"</br>");
    document.getElementById("links").innerHTML = x;
}
</script>
</body>
</html>

您需要使用带有全局标志的正则表达式:

x = x.replace(/http:'/'/example'.com'/ad'//g, "http://example.com/story/"); 
x = x.replace(/'n/g,"</br>");

请注意,您需要转义任何特殊字符。

g标志应该可以正常工作。尝试使用正则表达式时出现的问题可能与/需要在JavaScript正则表达式文本中转义有关。试试这个:

document.getElementById("links").innerHTML = document.getElementById("myTextarea")
  .value
  .replace(/http:'/'/example'.com'/ad'//g, "http://example.com/story/")
  .replace(/'n/g, "<br>");

replace函数将只替换第一个出现:

取自:http://www.w3schools.com/jsref/jsref_replace.asp

如果要替换值(而不是正则表达式),则只替换该值的第一个实例。要替换指定值的所有引用,请使用全局(g)修饰符(请参阅下面的"更多示例")。

要执行全局替换,应该在replace函数的第一个参数中使用正则表达式。在您的情况下:

x.replace(/'n/g, "</br>");

我希望它能帮助你!