How to capture the first word of a string and convert it to int? JQuery

I need to capture the first word in a string, and I need to convert it to an integer. How to do it using jQuery?

example : "223 Lorem Ipsum Dolor"

I need " 223 " and it must be converted to an integer ...

Any help would be appreciated.

+8
javascript jquery html
source share
4 answers

You can split the string based on any character (e.g. space) and then pass the first index to parseInt

 var str = "223 lorem"; var num = parseInt(str.split(' ')[0], 10); 

Demo

Note that parseInt accepts the second parameter, which is the base. If you leave this and try to analyze a number with a zero number, for example 09 , it will assume that you are in base 8 and will return 0, since 09 not a valid base 8 value.


Or, as John points out, using the unary + operator is a great way to convert a string to a number:

 var str = "223 lorem"; var num = +str.split(' ')[0]; 

Demo

+23
source share

Try it.

 var str = "223 Lorem Ipsum Dolor"; str = $.trim(str).split(" "); var num = parseInt(str[0], 10); 
+4
source share

I think it's better to use something like:

 var str = "223 Lorem Ipsum Dolor"; var matches = str.match(/(\d+)/); result = parseInt(matches[0]); 

Maybe you want to find some notes before \ d +

+2
source share

Try it...

 function getFirstNumber(str) { var matched = str.match(/^\d+/); if(matched) { return +matched[0]; // Get matched number (as string) and type cast to Number. } console.error("first word is not a number: '" + str + "'."); return -1; }; var str = "223 lorem"; getFirstNumber(str); 
0
source share

All Articles