1

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.

3 Answers 3

3

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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

woops! not the first time missing a ) has led to me pulling my hair out! Thanks
1

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.

2 Comments

Have you seen this -> regexhero.net/tester ? its also pretty damn good when working with regex.
Yeah, that's also good! Basically you just need a regex tester of some description, it'll save a lot of time as I'm sure you've found! :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.