简体   繁体   中英

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" />';

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM