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?
You can use the substring function:
var str = "12345.00"; str = str.substring(0, str.length - 1); // "12345.0"
This is the accepted answer, but as per the conversations below, the slice syntax is much clearer:
var str = "12345.00"; str = str.slice(0, -1); // "12345.0"
You can use slice! You just have to make sure you know how to use it. Positive #s are relative to the beginning, negative numbers are relative to the end.
s = s.substring(0, s.length - 4)
It unconditionally removes the last four characters from string
However, if you want to conditionally remove the last four characters, only if they are exactly
var re = /_bar$/; s.replace(re, "");
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):
var s = "your string"; var 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):
var s = "your_string"; var withoutLastChunk = s.slice(0, s.lastIndexOf("_")); // withoutLastChunk == "your"
For a number like your example, I would recommend doing this over
alert(parseFloat('12345.00').toFixed(1)); // 12345.0
Do note that this will actually round the number, though, which I would imagine is desired but maybe not:
alert(parseFloat('12345.46').toFixed(1)); // 12345.5
var string = 'foo_bar'; string = string.slice(0, -4); // Slice off last four characters here
This could be used to remove ‘_bar’ at end of a string, of any length.