最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript Regexp Search and Replace - Stack Overflow

programmeradmin2浏览0评论

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

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" />';
Share Improve this question edited Jul 19, 2011 at 17:36 pimvdb 155k80 gold badges311 silver badges356 bronze badges asked Jul 19, 2011 at 17:18 VinnyDVinnyD 3,5509 gold badges36 silver badges48 bronze badges 1
  • Is the whole string HTML content? – Dominic Barnes Commented Jul 19, 2011 at 17:20
Add a comment  | 

4 Answers 4

Reset to default 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");

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

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

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");
发布评论

评论列表(0)

  1. 暂无评论