开发者

Matching _{number} with Regex in javascript

I am trying the match part of an image src, an example would be:

images/preview_1.jpg

and I want to change _1 to say _6

so I’m trying to match _1

function ClickImgOf(filename, itemid){
   var re = new RegExp("(.+)_[0-9])\\.(gif|jpg|jpg|ashx|png)", "g");
   return filename.replace(re, "$1_"+itemid+".$2");
}

Is the function I have..

I know that only matches 0-开发者_运维问答9 but I was just trying to get something to work and even that didn't.

Its fair to say I do not know much about Regex at the moment.


You have an unmatched ) parenthesis there in your pattern. Is that what's throwing you off? Looks okay otherwise. If your problem is being able to match 2-or-more-digit numbers, try [0-9]+.

function ClickImgOf(filename, itemid){
   var re = new RegExp("(.+)_([0-9]+)\\.(gif|jpg|jpg|ashx|png)", "g");
   return filename.replace(re, "$1_"+itemid+".$3");
}


Try this:

(.+_)[0-9]+(\.(?:gif|jpg|jpg|ashx|png))

Then you can just do:

return filename.replace(re, "$1" + itemid + "$2");

Also, download and install this: http://www.ultrapico.com/ExpressoDownload.htm

It's invaluable when working with regular expressions.


You don't need to build your regex using the regex object, it's both easier and performs better to use a literal.

function ClickImgOf(filename, itemid) {
   return filename.replace(/_\d+\.(gif|jpg|jpg|ashx|png)$/g, '_'+itemid+'.$2');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜