How to select with regex?

3

I'm trying to format text of the following type

123,345,234   //tem que ficar 123345,234
abc,def,adf   //tem que ficar abcdef,adf
123,345,678,abc,qualquer,coisa    //tem que ficar 123345678abcqualquer,coisa

I need to remove all commas, except the last, how do I do this with regular expression in javascript?

    
asked by anonymous 22.01.2015 / 20:10

2 answers

3

Use the regex /,(?=[^,]*,)/g and the replace method:

var a = "123,345,234";   //tem que ficar 123345,234
var b = "abc,def,adf";   //tem que ficar abcdef,adf
var c = "123,345,678,abc,qualquer,coisa";    //tem que ficar 123345678abcqualquer,coisa

var a2 = a.replace(/,(?=[^,]*,)/g, "");
var b2 = b.replace(/,(?=[^,]*,)/g, "");
var c2 = c.replace(/,(?=[^,]*,)/g, "");

document.write(a2 + "<br/>");
document.write(b2 + "<br/>");
document.write(c2);
    
22.01.2015 / 20:20
3

You can do this only with javascript:

function arranjar(str){
    var partes = str.split(',');
    var ultima = partes.pop();
    return [partes.join(''), ultima].join(',');
}
arranjar('123,345,678,abc,qualquer,coisa') // dá "123345678abcqualquer,coisa"

To do this with regex is not simpler. But an example would look like this:

function arranjarComRegex(str){
    var partes = str.match(/(.*),(.*)/);
    var string = partes[1].replace(/,/g, '');
    return string + ',' + partes[2];
}

In this case regex (.*),(.*) captures two groups. In the first capture '123,345,678,abc,qualquer' where you need to remove the commas with .replace(/,/g, '') and the second catch group takes the last word, which then needs to be back in the string with string + ',' + partes[2] .

    
22.01.2015 / 20:17