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);
精彩评论