在javascript中全部替换

时间:2016-06-09 00:32:28

标签: javascript regex

如何在javascript中替换字符串中“http://localhost”的所有出现?

我有res=res.replace(/^http\:\/\/localhost, url);,但它不起作用。我该如何解决?

url是一个变量,但“localhost”是一个字符串。

更新

通过以下解决方案,我仍然得到:ReferenceError: localhost is not defined。我错过了什么?

更新2:

这是在页面上插入JS的(Perl)代码:

$form .=  qq|<script>res='$doc'; loc=document.location.href; url=loc.substring(0,loc.indexOf(":8080")); res=res.replace(/http\:\/\/localhost/g, url); document.location='data:text/html;charset:utf-8,' + res; </script>|;

2 个答案:

答案 0 :(得分:0)

res=res.replace(/http\:\/\/localhost/g, url);

&#39;克&#39;表示要替换所有。

答案 1 :(得分:0)

使用/ g替换字符串中的每一个匹配项

像这样的东西

str = str.replace(/http:\/\/localhost/g,'');