How to get a numerical value from a string containing numbers and characters

Is there a built-in getter method that can parse an int from a string ("23px")?

I know I can use substring and then parseInt , but I want to know if there is another way for this.

+4
source share
2 answers

parseInt will capture the first set of contiguous numbers:

 parseInt('23px'); 

returns 23.

If there is a chance that there will be leading zeros, use radix:

 parseInt('23px', 10); 

which is a good habit in general.

+8
source

parseInt can do this. Just use:

 var num = parseInt("23px", 10); 

He will analyze the whole part and ignore the rest.

+3
source

Source: https://habr.com/ru/post/1380335/


All Articles