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

前端 未结 9 1180
梦如初夏
梦如初夏 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:33
    'tro.lo.lo.lo.lo.lo.png'.replace(/([^\.]+).+(\.[^.]+)/, "$1.@x2$2")
    
    0 讨论(0)
  • 2020-12-13 17:34

    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
    
    0 讨论(0)
  • 2020-12-13 17:35

    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);
    ​
    
    0 讨论(0)
  • 2020-12-13 17:35

    You could simply do like this,

    > "tro.lo.lo.lo.lo.lo.zip".replace(/^(.*)\./, "$1@2x");
    'tro.lo.lo.lo.lo.lo@2xzip'
    
    0 讨论(0)
  • 2020-12-13 17:38

    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('.');
    
    0 讨论(0)
  • 2020-12-13 17:40

    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.

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