Whats a simple way to delete the last two characters of a string?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- how to split a list into a given number of sub-lis
This does exactly what you ask: remove last two chars of a string:
Surprisingly, the substring method
s.substr(0, s.length-2);
is actually quite a bit faster for removing thepx
(yes it isn't as clean looking, and if there is a space it will remain --"250px" -> "250"
vs"250 px" -> "250 "
).If you want to account for spaces (which you probably should) then using the
.trim()
function will actually slow down thesubstr
test enough that theparseInt
method actually becomes superior.An added benefit of using
parseInt(s, 10)
is that you also get a type conversion and can immediately start to apply it to mathematical functions.So in the end, it really depends on what you plan on doing with the result.
substr
method without a trim would probably be your best bet.s.substr(0, s.length-2) == 0
, then using thesubstr
method would be best, as"250 " == 250
(even with the space) will result astrue
parseInt
route.http://jsperf.com/remove-px-from-coord
The tests on jspref account for a space. I also tried a
s.split('px')[0]
ands.replace(/ *px/g, '')
function, both found to be slower.Feel free to add additional test cases.
use
where 10 is the radix defining
parseInt
is parsing to a decimal valueuse parseInt but don't use parseInt without a radix
The parseInt() function parses a string and returns an integer.
The signature is
parseInt(string, radix)
The second argument forces parseInt to use a base ten numbering system.
why? if $(this).attr('num') would be "08" parsInt without a radix would become 0
Check http://www.w3schools.com/jsref/jsref_substr.asp In your case would be something like
To convert a pixel value without the "px" at the end. use parseFloat.
Note: If you use parseInt, the vaue will be correct if the value is an integer. If the value is a decimal one like 245.50px, then the value will be rounded to 245.
I prefer:
"245px".replace(/px/,'')*1
since it's not surrounding the input.
Also, the
*1
is for casting it to int.