Alex Rivera | Logout

How do I chop/slice/trim off last character in string using Javascript?

Asked 2009-06-04T20:31:53.540
2623

I have a string, 12345.00, and I would like it to return 12345.0.

I have looked at trim, but it looks like it is only trimming whitespace and slice which I don't see how this would work. Any suggestions?

Edit
Report

4 Answers

182

The easiest method is to use the slice method of the string, which allows negative positions (corresponding to offsets from the end of the string):

const s = "your string";
const withoutLastFourChars = s.slice(0, -4);

If you needed something more general to remove everything after (and including) the last underscore, you could do the following (so long as s is guaranteed to contain at least one underscore):

const s = "your_string";
const withoutLastChunk = s.slice(0, s.lastIndexOf("_"));
console.log(withoutLastChunk);

answered 2010-08-30T10:15:57.770
25

A regular expression is what you are looking for:

let str = "foo_bar";
console.log(str.replace(/_bar$/, ""));

answered 2010-08-30T03:09:02.557
9

1. (.*), captures any character multiple times:

console.log("a string".match(/(.*).$/)[1]);

2. ., matches last character, in this case:

console.log("a string".match(/(.*).$/));

3. $, matches the end of the string:

console.log("a string".match(/(.*).{2}$/)[1]);

answered 2012-12-28T04:38:31.777
5

If you want to do generic rounding of floats, instead of just trimming the last character:

var float1 = 12345.00,
    float2 = 12345.4567,
    float3 = 12345.982;

var MoreMath = {
    /**
     * Rounds a value to the specified number of decimals
     * @param float value The value to be rounded
     * @param int nrDecimals The number of decimals to round value to
     * @return float value rounded to nrDecimals decimals
     */
    round: function (value, nrDecimals) {
        var x = nrDecimals > 0 ? 10 * parseInt(nrDecimals, 10) : 1;
        return Math.round(value * x) / x;
    }
}

MoreMath.round(float1, 1) => 12345.0
MoreMath.round(float2, 1) => 12345.5
MoreMath.round(float3, 1) => 12346.0

EDIT: Seems like there exists a built in function for this, as Paolo points out. That solution is obviously much cleaner than mine. Use parseFloat followed by toFixed

answered 2009-06-04T20:47:07.550

Your Answer