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
asked Jun 17, 2010 at 19:57
Tegan Snyder
7611 gold badge9 silver badges20 bronze badges
3 Answers 3
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>
answered Jun 17, 2010 at 19:59
Mark Byers
844k202 gold badges1.6k silver badges1.5k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Jun 17, 2010 at 19:59
Robusto
32k8 gold badges59 silver badges79 bronze badges
2 Comments
Robusto
And, as @Mark Byers points out, you need to assign the result to
str :)Tegan Snyder
syntax highlighting in dreamweaver isn't liking it: str = str.replace(/href="\/newsroom\/g, 'href=\"intranet/newsroom\"');
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);
answered Jun 17, 2010 at 20:19
Thea
8,0656 gold badges30 silver badges41 bronze badges
2 Comments
Tegan Snyder
it works but doesn't leave the image name on the end of the url [code] <script> str = '<A href="/newsroom/some_image.jpg">photo</A>'; str = str.replace(/href="\/newsroom/g, 'href=\"intranet/newsroom\"'); document.write(str); </script> [code]
Tegan Snyder
still only getting me a link called photo that goes to intranet/newsroom when it should go to intranet/newsroom/some_image.jpg <code> <script> str = '<A href="/newsroom/some_image.jpg">photo</A>'; str = str.replace(/href="\/newsroom/g, 'href=\"intranet/newsroom\"'); document.write(str); </script> </code>
lang-js
str.replace('/href="/newsroom/g', 'href="http://intranet/newsroom"');