JavaScript chop/slice/trim off last character in string
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.
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, "");
链接地址: http://www.djcxy.com/p/4526.html
上一篇: 在Python中理解kwargs