views:

66

answers:

3

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

+2  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.

Robusto
And, as @Mark Byers points out, you need to assign the result to `str` :)
Robusto
syntax highlighting in dreamweaver isn't liking it: str = str.replace(/href="\/newsroom\/g, 'href=\"http://intranet/newsroom\"');
Tegan Snyder
i just made an edit and added my code
Tegan Snyder
+2  A: 

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"&gt;photo&lt;/A&gt;
Mark Byers
A: 

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);
Teddy
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=\"http://intranet/newsroom\"'); document.write(str);</script>[code]
Tegan Snyder
See my updated answer.
Teddy
still only getting me a link called photo that goes to http://intranet/newsroom when it should go to http://intranet/newsroom/some_image.jpg<code> <script>str = '<A href="/newsroom/some_image.jpg">photo</A>'; str = str.replace(/href="\/newsroom/g, 'href=\"http://intranet/newsroom\"'); document.write(str); </script></code>
Tegan Snyder
I updated again
Teddy