Remove all occurrences except last?

后端 未结 9 1567
深忆病人
深忆病人 2020-12-03 07:06

I want to remove all occurrences of substring = . in a string except the last one.

E.G:

1.2.3.4

should become:

相关标签:
9条回答
  • 2020-12-03 07:55

    You can do something like this:

    var str = '1.2.3.4';
    var last = str.lastIndexOf('.');
    var butLast = str.substring(0, last).replace(/\./g, '');
    var res = butLast + str.substring(last);
    

    Live example:

    • http://jsfiddle.net/qwjaW/
    0 讨论(0)
  • 2020-12-03 07:55

    You could reverse the string, remove all occurrences of substring except the first, and reverse it again to get what you want.

    0 讨论(0)
  • 2020-12-03 07:56

    A replaceAllButLast function is more useful than a removeAllButLast function. When you want to remove just replace with an empty string:

    function replaceAllButLast(str, pOld, pNew) {
      var parts = str.split(pOld)
      if (parts.length === 1) return str
      return parts.slice(0, -1).join(pNew) + pOld + parts.slice(-1)
    }
    
    var test = 'hello there hello there hello there'
    test = replaceAllButLast(test, ' there', '')
    
    console.log(test) // hello hello hello there

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