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 -> tro.lo@2x.png
Here’s what I have so far but it won’t match anything…
str = "http://example.com/image.png";
str.replace(/.([^.]*)$/, " @2x.");
any suggestions?
You do not need a regex for this.
String.lastIndexOfwill do.See it in action.
Update: A regex solution, just for the fun of it:
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.