RegEx that will match the last occurrence of dot in a string

前端 未结 9 1181
梦如初夏
梦如初夏 2020-12-13 16:55

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 repla

相关标签:
9条回答
  • 2020-12-13 17:42

    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.

    0 讨论(0)
  • 2020-12-13 17:45

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

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

    0 讨论(0)
  • 2020-12-13 17:53

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

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

    0 讨论(0)
提交回复
热议问题