2016-06-09 59 views
0

如何在JavaScript中的字符串中替换所有出现的“http://localhost”?我有res=res.replace(/^http\:\/\/localhost, url);,但它不起作用。我如何解决它?全部替换为javascript

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

UPDATE:

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

更新2:

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

$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

声明未完成。 – Dere0405

+0

@ Dere0405我相信我现在完成了。 – kepj

+0

那么,如果你使用下面的解决方案得到这个结果,那么你就错了。 – epascarello

回答

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

'G' 表示全部更换。

+0

我收到了:'ReferenceError:localhost is not defined' – kepj

+0

请注意,在正则表达式开头的^确保它只会匹配一次(在字符串的开始处)。 – stewbasic

0

使用/克至每替换发生在你的字符串

像这样的事情

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

我得到:'ReferenceError:localhost没有定义'。显然我没有一个变量'localhost'。 – kepj

+0

@kepj代码中没有变量'localhost'。它是一个正则表达式,它不是一个变量。 – Barmar

+0

@Barmar控制台抱怨我没有变量'localhost'。我知道我没有一个。我不明白为什么它抱怨! – kepj