Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grab first word of string and convert it to int? jQuery

I need to grab first word in string and I need to convert it to integer. How to do this using jQuery?

example : "223 Lorem Ipsum Dolor"

I need "223" and it must be converted into integer...

Any help would be appreciated.

like image 387
BBee Avatar asked Jan 27 '12 20:01

BBee


1 Answers

You can split a string based on any character (like a space), then pass the first index to parseInt

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

DEMO

Note that parseInt takes a second parameter, which is the radix. If you leave that off, and try to parse a number with a leading zero, like 09, it'll assume you're in base 8, and will return 0, since 09 isn't a valid base-8 value.


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

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

DEMO

like image 138
Adam Rackis Avatar answered Sep 21 '22 20:09

Adam Rackis