Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  80] [ 2]  / answers: 1 / hits: 110086  / 12 Years ago, thu, june 21, 2012, 12:00:00

I have a filename that can have multiple dots in it and could end with any extension:



tro.lo.lo.lo.lo.lo.png


I need to use a regex to replace the last occurrence of the dot with another string like @2x and then the dot again (very much like a retina image filename) i.e.:



tro.lo.png -> [email protected]


Here's what I have so far but it won't match anything...



str = http://example.com/image.png;
str.replace(/.([^.]*)$/, @2x.);


any suggestions?


More From » jquery

 Answers
18

You do not need a regex for this. String.lastIndexOf will do.



var str = 'tro.lo.lo.lo.lo.lo.zip';
var i = str.lastIndexOf('.');
if (i != -1) {
str = str.substr(0, i) + @2x + str.substr(i);
}


See it in action.



Update: A regex solution, just for the fun of it:



str = str.replace(/.(?=[^.]*$)/, @2x.);


Matches a literal dot and then asserts ((?=) is positive lookahead) that no other character up to the end of the string is a dot. The replacement should include the one dot that was matched, unless you want to remove it.


[#84760] Wednesday, June 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
richardaydenc

Total Points: 148
Total Questions: 125
Total Answers: 98

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;