Remove all occurrences except last?

后端 未结 9 1572
深忆病人
深忆病人 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条回答
  •  Happy的楠姐
    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/

提交回复
热议问题