开发者

Javascript Replace text in string

I'm having some troubles getting regex to replace all occurances of a string within a string.

**What to replace:**
href="/newsroom

**Replace with this:**
href="http://intranet/newsroom

This isn't working:

str.replace(开发者_开发技巧/href="/newsroom/g, 'href="http://intranet/newsroom"');

Any ideas?

EDIT

My code:

str = '<A href="/newsroom/some_image.jpg">photo</A>';
str = str.replace('/href="/newsroom/g', 'href="http://intranet/newsroom"');
document.write(str);

Thanks, Tegan


Three things:

  • You need to assign the result back to the variable otherwise the result is simply discarded.
  • You need to escape the slash in the regular expression.
  • You don't want the final double-quote in the replacement string.

Try this instead:

str = str.replace(/href="\/newsroom/g, 'href="http://intranet/newsroom')

Result:

<A href="http://intranet/newsroom/some_image.jpg">photo</A>


You need to escape the forward slash, like so:

str.replace(/href="\/newsroom\/g, 'href=\"http://intranet/newsroom\"');

Note that I also escaped the quotes in your replacement argument.


This should work

 str.replace(/href="\/newsroom/g, 'href=\"http://intranet/newsroom\"')

UPDATE:
This will replase only the given string:

str = '<A href="/newsroom/some_image.jpg">photo</A>';
str = str.replace(/\/newsroom/g, 'http://intranet/newsroom');
document.write(str);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜