How to delete “px” from 245px

2019-01-30 07:42发布

Whats a simple way to delete the last two characters of a string?

7条回答
倾城 Initia
2楼-- · 2019-01-30 08:04

This does exactly what you ask: remove last two chars of a string:

s.substr(0, s.length-2);
查看更多
forever°为你锁心
3楼-- · 2019-01-30 08:04

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 the substr method would be best, as "250 " == 250 (even with the space) will result as true
  • 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.

查看更多
Lonely孤独者°
4楼-- · 2019-01-30 08:07

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

查看更多
趁早两清
5楼-- · 2019-01-30 08:07

Check http://www.w3schools.com/jsref/jsref_substr.asp In your case would be something like

string.substr(0, string.length - 2)
查看更多
劫难
6楼-- · 2019-01-30 08:09

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.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-30 08:12

I prefer: "245px".replace(/px/,'')*1

since it's not surrounding the input.

Also, the *1 is for casting it to int.

查看更多
登录 后发表回答