最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to remove suffix from string? - Stack Overflow

programmeradmin0浏览0评论

How can I remove the following suffix:

  1. px
  2. %
  3. em

from some string if it contains that suffix ?
Like enter I get string which can be measure of width of div and that can ends with 'px', '%', 'em' and can also be without, so I need to remove suffix if it exists.

How can I remove the following suffix:

  1. px
  2. %
  3. em

from some string if it contains that suffix ?
Like enter I get string which can be measure of width of div and that can ends with 'px', '%', 'em' and can also be without, so I need to remove suffix if it exists.

Share Improve this question edited May 7, 2012 at 12:25 Dor Cohen 17.1k24 gold badges95 silver badges161 bronze badges asked May 7, 2012 at 12:22 DamirDamir 56.4k98 gold badges251 silver badges368 bronze badges 2
  • You actually need to get the numeric part... – Itay Moav -Malimovka Commented May 7, 2012 at 12:24
  • 1 @Damir, if this problem was solved consider to accept an answer – Fabrizio Calderan Commented Oct 6, 2012 at 12:59
Add a ment  | 

2 Answers 2

Reset to default 7
var s = "34em";
parseInt(s, 10); // returns 34

this works for em, px, %, pt... and any other suffix even if it has a space before.

Use parseFloat() instead if you have non-integer values

var s = "81.56%";
parseFloat(s); // returns 81.56

You can use a regular expression to get a string with only the digits:

var s = input.replace(/\D+/g, '');

You can parse the string as a number, that will ignore the non-numeric characters at the end:

var n = parseInt(input, 10);
发布评论

评论列表(0)

  1. 暂无评论