1

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
  • I'm not sure if you copied it correcly, but you have missed the single quotation marks in the first string. it should be str.replace('/href="/newsroom/g', 'href="http://intranet/newsroom"'); Commented Jun 17, 2010 at 19:59
  • Wierd it doesnt work for me: str = str.replace('/href="/newsroom/g', 'href="intranet/newsroom"'); Commented Jun 17, 2010 at 20:12

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

And, as @Mark Byers points out, you need to assign the result to str :)
syntax highlighting in dreamweaver isn't liking it: str = str.replace(/href="\/newsroom\/g, 'href=\"intranet/newsroom\"');
1

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);

2 Comments

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]
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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.