问题
Whats a simple way to delete the last two characters of a string?
回答1:
To convert 245px
in 245 just run:
parseInt('245px', 10);
It retains only leading numbers and discards all the rest.
回答2:
use
var size = parseInt('245px', 10);
where 10 is the radix defining parseInt
is parsing to a decimal value
use 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.
- The default input type for ParseInt() is decimal (base 10).
- If the number begins in "0", it is assumed to be octal (base 8).
- If it begins in "0x", it is assumed to be hexadecimal
why? if $(this).attr('num') would be "08" parsInt without a radix would become 0
回答3:
To convert a pixel value without the "px" at the end. use parseFloat.
parseFloat('245px', 10);//returns 245
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.
回答4:
This does exactly what you ask: remove last two chars of a string:
s.substr(0, s.length-2);
回答5:
Surprisingly, the substring method s.substr(0, s.length-2);
is actually quite a bit faster for removing the px
(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 the substr
test enough that the parseInt
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.
- If it is display only, then using the
substr
method without a trim would probably be your best bet. - If you're just trying to see if the value without px is the same as another value
s.substr(0, s.length-2) == 0
, then using thesubstr
method would be best, as"250 " == 250
(even with the space) will result astrue
- If you want to account for the possibility of a space, add it to another value, or to compute something with it, then you may want to consider going with the
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]
and s.replace(/ *px/g, '')
function, both found to be slower.
Feel free to add additional test cases.
回答6:
Check http://www.w3schools.com/jsref/jsref_substr.asp In your case would be something like
string.substr(0, string.length - 2)
回答7:
I prefer:
"245px".replace(/px/,'')*1
since it's not surrounding the input.
Also, the *1
is for casting it to int.
回答8:
Although parseInt() is a good option but still it is good to have many other solutions
var pixels = '245px';
Number(pixels.replace('px', ''));
来源:https://stackoverflow.com/questions/4860244/how-to-delete-px-from-245px