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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With