字符串替换只替换第一个匹配项,可以'不要让它全球化
String replace replaces only first match, can't make it global
请帮我,因为我不懂编程。我应该怎么做才能使它替换所有字符串匹配?如果我写/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>");
我希望它能帮助你!
相关文章:
- 无法从 jQuery RSS Feed 中的 localStorage 动态替换类
- 我如何找到一个句子中的所有空格并替换忽略它们
- 如何用更合适的内容替换document.write
- 是否有任何方法可以使用jQuery替换在数组中定义值的文本
- 在DOM中查找一个模式并替换它's的内容使用jquery
- 用空格替换下划线PHP
- str.split(someString).join(someOtherString)是否等效于替换
- 使用javascript的图像替换循环
- window.location替换并传递URL历史记录条目中的变量
- 替换标记中的属性
- 指令的模板必须只有一个根元素:With restrict E&替换true
- AngularJs对ng消息的自定义替换
- 用超链接替换URLS
- 用cdata标记替换脚本标记
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- 在javascript中,I'我很难弄清楚如何让regex只替换捕获而不替换匹配
- 替换url中变量的值
- 我希望在不替换现有变量的情况下恢复localStorage中的变量
- Wordpress:替换源(域名)链接
- 字符串替换只替换第一个匹配项,可以'不要让它全球化