Reputation: 13
I'm using javascript to append a string to a variable (adding specific image size to a slider on mobile devices).
Here's the line I'm using.
var newsrc = src.substring(0, src.lastIndexOf(".")) + "-420x320" + src.substring(src.lastIndexOf("."));
However there are some cases where the image src has another size and in this case I would like to remove that size and add the one above.
Example: Both
http://domain.com/10001428289243jpg-700x703.jpg and
http://domain.com/10001428289243jpg.jpg
Needs to be:
http://domain.com/10001428289243jpg-420x320.jpg
What would you use in this case?
Upvotes: 0
Views: 76
Reputation: 646
I'd stick in a quick replace that matches the -#x#
pattern and replaces it with a blank.
var newsrc = src.replace(/(-\d+x\d+)/,"").substring(0, src.lastIndexOf(".")) + "-420x320" + src.substring(src.lastIndexOf("."));
Upvotes: 0
Reputation: 1442
FIDDLE LINK: http://jsfiddle.net/9u8m9oob/1/
You can achieve the same using below way also:
var str1='http://domain.com/10001428289243jpg.jpg';
var str2='http://domain.com/10001428289243jpg-700x703.jpg';
var regex=/^(http:\/\/domain\.com\/)(\d+jpg)(.)*(\.jpg)$/g;
var result= str1.replace(regex,"$1$2-420x320$4");
console.log(result); // gives output as http://domain.com/10001428289243jpg-420x320.jpg
Upvotes: 0
Reputation: 89547
All you need is to build a pattern with an optional part:
src = src.replace(/(?:-\d+x\d+)?\.jpg$/, '-420x320.jpg');
where (?:-\d+x\d+)?
is an optional non-capturing group and $
is an anchor for the end of the string.
Upvotes: 3