简体   繁体   中英

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');
}

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