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?
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"
str = str.substring(0, str.length -1);
– Doug Molineux
Jul 15 '11 at 16:10
slice
& substring
methods are all most the same; except the that the slice()
accepts a negative index, relative to the end of the string, but not the substring
, it throws out-of-bound
error
– Amol M Kulkarni
Apr 9 '13 at 9:45
substring
is 11% faster than slice
. jsperf.com/js-slice-vs-substring-test
– BenR
Apr 16 '14 at 15:53
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.
js>"12345.00".slice(0,-1)
12345.0
You can use the substring method of JavaScript string objects:
s = s.substring(0, s.length - 4)
It unconditionally removes the last four characters from string s
.
However, if you want to conditionally remove the last four characters, only if they are exactly _bar
:
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 substring
:
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
Using JavaScript's slice function:
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.
A regular expression is what you are looking for:
var str = "foo_bar";
alert(str.replace(/_bar$/, ""));
"a string".match(/(.*).$/)[1] // => a strin
"a string".match(/(.*).$/) // returns ["a string", "a strin"]
"a string".match(/(.*).{2}$/)[1] // to get two chars off => a stri
debris = string.split("_") //explode string into array of strings indexed by "_"
debris.pop(); //pop last element off the array (which you didn't want)
result = debris.join("_"); //fuse the remainng items together like the sun
Here is an alternative that i don't think i've seen in the other answers, just for fun.
var strArr = "hello i'm a string".split("");
strArr.pop();
document.write(strArr.join(""));
Not as legible or simple as slice or substring but does allow you to play with the string using some nice array methods, so worth knowing.
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
var str = "test!";
var newStr = str.slice(0,-1); //test
if(str.substring(str.length - 4) == "_bar")
{
str = str.substring(0, str.length - 4);
}
https://jsfiddle.net/invos/w3zeqv6v/
Just use trim if you don't want spaces
"11.01 °C".slice(0,-2).trim()
In cases where you want to remove something that is close to the end of a string (in case of variable sized strings) you can combine slice() and substr().
I had a string with markup, dynamically built, with a list of anchor tags separated by comma. The string was something like:
var str = "<a>text 1,</a><a>text 2,</a><a>text 2.3,</a><a>text abc,</a>";
To remove the last comma I did the following:
str = str.slice(0, -5) + str.substr(-4);
@Jason S:
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.
js>"12345.00".slice(0,-1) 12345.0
Sorry for my graphomany but post was tagged 'jquery' earlier. So, you can't use slice() inside jQuery because slice() is jQuery method for operations with DOM elements, not substrings ... In other words answer @Jon Erickson suggest really perfect solution.
However, your method will works out of jQuery function, inside simple Javascript. Need to say due to last discussion in comments, that jQuery is very much more often renewable extension of JS than his own parent most known ECMAScript.
Here also exist two methods:
as our:
string.substring(from,to)
as plus if 'to' index nulled returns the rest of string. so:
string.substring(from)
positive or negative ...
and some other - substr() - which provide range of substring and 'length' can be positive only:
string.substr(start,length)
Also some maintainers suggest that last method string.substr(start,length)
do not works or work with error for MSIE.
.slice
on a variable that is a string, it's going to do just what the OP wanted. It doesn't matter if it's "inside jQuery" and there is no way it could "interfere" in any way unless you overwrite String.prototype
with jQuery, which I am sure will prevent ANY javascript code from working. Your answer just says that other answer is not good and the argument you provide is incorrect.
– naugtur
Dec 5 '12 at 17:18
.data
manipulation and end up with this "string"), which if you called slice
on it, would not do what you want. That said, this isn't really a helpful answer.
– mAAdhaTTah
Apr 25 '16 at 18:09
Try this:
<script>
var x="foo_foo_foo_bar";
for (var i=0; i<=x.length; i++) {
if (x[i]=="_" && x[i+1]=="b") {
break;
}
else {
document.write(x[i]);
}
}
</script>
You can also try the live working example on http://jsfiddle.net/informativejavascript/F7WTn/87/.
Use substring to get everything to the left of _bar. But first you have to get the instr of _bar in the string:
str.substring(3, 7);
3 is that start and 7 is the length.
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Math.round('0.5') === 1
;) – TWiStErRob Jul 18 '15 at 12:46