5

How can I use javascript regexp to do a case insensitive, global search and replace on a string with the following pattern:

[media id="5"] or [Media id=5]

and replace entirely with:

http://someurl/?somevar=THE_ID_FROM_THE_PATTERN

So basically, something like this:

var mystring = '<img src="[media id=5]" />';

Should be converted to:

var newstring = '<img src="http://someurl/?somevar=5" />';
1
  • Is the whole string HTML content? Commented Jul 19, 2011 at 17:20

4 Answers 4

15

You need to capture the number, using parentheses, and add it back in with $1 when you replace. Also, based on your example, it should be case insensitive (//i) and the quotation marks are optional.

var mystring = '<img src="[media id=5]" />';
var re = /\[media id="?(\d+)"?\]/gi;
mystring.replace(re, "http://someurl/?somevar=$1");
Sign up to request clarification or add additional context in comments.

4 Comments

yeah, the biggest issue i was having is with the optional question marks. thanks a bunch!
how about if there are multiple [media id=X] tags in the string? would i just need to add "g" to the following statement: var re = /[media id="?(\d+)"?]/ig;
Yes, but $1 is the first match so you'd have to adjust the replacement string somehow.
Actually, I just ran the code and it looks like it works with the global flag.
1

You can use:

var mystring = '<img src="[media id=5]" />';
mystring.replace(/\[media id=5\]/gi, 'http://someurl/?somevar=5').toString();

AND/OR

var mystring = '<img src="[media id=\"5\"]" />';
mystring.replace(/\[media id=\"5\"\]/gi, 'http://someurl/?somevar=5').toString();

Comments

1

var regexp=/\[media id="5"\]/gi;

Comments

1

The right way, I think, would be something like this:

var regexp = /\[[mM]edia\ id\=\"\d+\"\]/g;
var mystring = '<img src="[media id=5]" />';
var newstring = mystring.replace(regexp, "http://someurl/?somevar=$1");

2 Comments

I guess I'm missing something - why not?
@AleksG because the quote characters in regexp are not optional. Tack on a question mark to them to allow 0 or 1 occurrence.

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.