Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regexp Search and Replace

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" />';
like image 851
VinnyD Avatar asked Dec 03 '22 07:12

VinnyD


1 Answers

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");
like image 63
gpojd Avatar answered Dec 05 '22 20:12

gpojd