Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all occurrences except last?

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

E.G:

1.2.3.4

should become:

123.4
like image 315
lisovaccaro Avatar asked Mar 14 '12 01:03

lisovaccaro


3 Answers

You can use regex with positive look ahead,

"1.2.3.4".replace(/[.](?=.*[.])/g, "");
like image 196
mpapec Avatar answered Oct 31 '22 12:10

mpapec


2-liner:

function removeAllButLast(string, token) {
    /* Requires STRING not contain TOKEN */
    var parts = string.split(token);
    return parts.slice(0,-1).join('') + token + parts.slice(-1)
}

Alternative version without the requirement on the string argument:

function removeAllButLast(string, token) {
    var parts = string.split(token);
    if (parts[1]===undefined)
        return string;
    else
        return parts.slice(0,-1).join('') + token + parts.slice(-1)
}

Demo:

> removeAllButLast('a.b.c.d', '.')
"abc.d"

The following one-liner is a regular expression that takes advantage of the fact that the * character is greedy, and that replace will leave the string alone if no match is found. It works by matching [longest string including dots][dot] and leaving [rest of string], and if a match is found it strips all '.'s from it:

'a.b.c.d'.replace(/(.*)\./, x => x.replace(/\./g,'')+'.')

(If your string contains newlines, you will have to use [.\n] rather than naked .s)

like image 36
ninjagecko Avatar answered Oct 31 '22 12:10

ninjagecko


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/
like image 7
icyrock.com Avatar answered Oct 31 '22 11:10

icyrock.com