Mr. Jo
Mr. Jo

Reputation: 5261

Remove all decimals from a string except the last one

How do I remove all the decimals in a string except for the last one in jQuery or JavaScript?

Original strings

1.233.543.00
456.00
1.234.00

Desired results

1233543.00
456.00
1234.00

My jQuery code to extract the values:

jQuery('.addui-slider-handle-l span').text()

Upvotes: 3

Views: 283

Answers (4)

lacostenycoder
lacostenycoder

Reputation: 11196

Here you can run this in a console on this page and get what you want for fun

$('#question').find('code').text().split(/\s/).slice(0,3).map(n => n.replace(/\.(?=.*\.)/g, ""))

Upvotes: 0

CrayonViolent
CrayonViolent

Reputation: 32532

Not sure if it's more efficient than the pure regex solution presented, but I know in general a lot of people are shy around regex, so here is a non-regex alternative.

Logic is to split the string at the dots, insert the last dot back in, and then join back to a string.

var x = "1.233.543.00".split('.');
x.length>1 && x.splice(-1,0,'.');
x = x.join('');

Upvotes: 0

Ultimate RA
Ultimate RA

Reputation: 51

function text(string){

var arrayDots=string.split(".")

var lastPart= arrayDots[arrayDots.length-1];

    var subresult="";

    for(var i=0; i<arrayDots.length-1; i++){
       subresult=subresult+arrayDots[i]; 
    }
     var result= subresult+"."+lastPart;

    console.log(result);
}  

This is not the easiest way but you can get the logic

Upvotes: 1

AgileFox
AgileFox

Reputation: 174

Try this using this on the string:

.replace(/[.](?=.*[.])/g, "");

Upvotes: 5

Related Questions