68

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?

1
  • You need a negative lookahead if you want to do it with regex but you really shouldn't Jun 21, 2012 at 8:12

9 Answers 9

118

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.

8
  • That returns an integer of the position where that character is, right?
    – alt
    Jun 21, 2012 at 8:13
  • How can I use that integer with .replace() ?
    – alt
    Jun 21, 2012 at 8:13
  • @JacksonGariety: You don't need to. String.substr will round things up.
    – Jon
    Jun 21, 2012 at 8:14
  • Cool answer! Why is this better/more efficient/less code than a regex?
    – alt
    Jun 21, 2012 at 8:16
  • 3
    @JacksonGariety. It's a lot more readable, and little bit faster.
    – gdoron
    Jun 21, 2012 at 8:17
32

Just use special replacement pattern $1 in the replacement string:

console.log("tro.lo.lo.lo.lo.lo.png".replace(/\.([^.]+)$/, "@2x.$1"));
// "[email protected]"

4
  • 2
    Correctly answers OPs question.
    – Qtax
    Jun 21, 2012 at 8:26
  • 2
    @Qtax: Not quite, because it won't work if the last dot is also the very last character.
    – Jon
    Jun 21, 2012 at 8:26
  • @Jon, true. Almost korrect then. ;) But /\.([^.]*)$/ does it, no need for lookarounds.
    – Qtax
    Jun 21, 2012 at 8:32
  • 1
    I am not sure if a filename could have a . as the very last character.
    – Salman A
    Jun 21, 2012 at 9:44
6

You can use the expression \.([^.]*?):

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

You need to reference the $1 subgroup to copy the portion back into the resulting string.

3
  • I think this needs another period at the end of "$1@2x" to work, right?
    – alt
    Jun 21, 2012 at 8:14
  • Was a bit hasty with that answer — fixed it to make more sense w.r.t. your original regex
    – user193476
    Jun 21, 2012 at 8:16
  • I think you are missing a . in the replacement string. I prefer escaping ., but character class may be easier to read. .replace(/(.*)\./, "$1@2x."). Anyway, +1 for a simple solution using the greedy property of * quantifier.
    – nhahtdh
    Jun 21, 2012 at 8:17
5

working demo http://jsfiddle.net/AbDyh/1/

code

var str = 'tro.lo.lo.lo.lo.lo.zip',
    replacement = '@2x.';
str = str.replace(/.([^.]*)$/, replacement + '$1');

$('.test').html(str);

alert(str);​
6
  • 1
    Not quite. the output is missing a dot.
    – gdoron
    Jun 21, 2012 at 8:16
  • 1
    Output should be [email protected] You output tro.lo.lo.lo.lo.lo@2xzip
    – gdoron
    Jun 21, 2012 at 8:19
  • @gdoron lol 35 second difference :) cheers updated version here jsfiddle.net/AbDyh/1
    – Tats_innit
    Jun 21, 2012 at 8:20
  • @gdoron you da man - by the way I was thinking when you will apply for moderator role man! anyhow SO is not chat applet but just a recommendation!
    – Tats_innit
    Jun 21, 2012 at 8:24
  • Not soon... I don't want the job, nor have the time. Cheers. :)
    – gdoron
    Jun 21, 2012 at 8:25
3

To match all characters from the beginning of the string until (and including) the last occurence of a character use:

^.*\.(?=[^.]*$)  To match the last occurrence of the "." character

^.*_(?=[^.]*$)   To match the last occurrence of the "_" character
2

Use \. to match a dot. The character . matches any character.

Therefore str.replace(/\.([^\.]*)$/, ' @2x.').

2
  • 1
    Try your code: "tro.lo.lo.lo.lo.lo.zip".replace(/\.([^\.]*)$/, ' @2x.') It doesn't work. Sorry.
    – gdoron
    Jun 21, 2012 at 8:15
  • Cool, did not know that about regex
    – alt
    Jun 21, 2012 at 8:16
1

You could simply do like this,

> "tro.lo.lo.lo.lo.lo.zip".replace(/^(.*)\./, "$1@2x");
'tro.lo.lo.lo.lo.lo@2xzip'
1

Why not simply split the string and add said suffix to the second to last entry:

var arr = 'tro.lo.lo.lo.lo.lo.zip'.split('.');
arr[arr.length-2] += '@2x';
var newString = arr.join('.');
1
'tro.lo.lo.lo.lo.lo.png'.replace(/([^\.]+).+(\.[^.]+)/, "$1.@x2$2")

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.