Remove all occurrences except last?

后端 未结 9 1569
深忆病人
深忆病人 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: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

提交回复
热议问题