我在使用正则表达式替换字符串中出现的所有字符串时遇到了一些麻烦。
**What to replace:**
href="/newsroom
**Replace with this:**
href="http://intranet/newsroom
这不起作用:
str.replace(/href="/newsroom/g, 'href="http://intranet/newsroom"');
有什么想法吗?
编辑
我的代码:
str = '<A href="/newsroom/some_image.jpg">photo</A>';
str = str.replace('/href="/newsroom/g', 'href="http://intranet/newsroom"');
document.write(str);
谢谢, 泰根
最佳答案
三件事:
- 您需要将结果分配回变量,否则结果将被丢弃。
- 您需要对正则表达式中的斜杠进行转义。
- 您不想在替换字符串中使用最后的双引号。
试试这个:
str = str.replace(/href="\/newsroom/g, 'href="http://intranet/newsroom')
结果:
<A href="http://intranet/newsroom/some_image.jpg">photo</A>
关于Javascript 替换字符串中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3065156/