Seperate a number (int) from a string in Javascript

Seperating a number or integer from a string is a common task in any coding language. I was in the middle of some mootool’in and i was about to go down the usual route when i rushed off to google a better way to do it. Thanks to stackoverflow i found it. Regular expressions!

Seperating a number or integer from a string is a common task in any coding language including javascript. It’s one of those times when you just wish code knew what you were trying to do…

Imagine you have a string:

var myString = "123 Hello World";

I was in the middle of some mootool’in and i was about to go down the usual route of:

var myNumber = myString.substring(0,myString.indexOf(' '));

when i rushed off to google a better way to do it. Thanks to stackoverflow i found it. Regular expressions! I have no idea how to write them but i can appreciate them. The following expressions get the first integer within a string:

("123 Hello World 4").replace(/(^\d+)(.+$)/i,'$1'); //=> '123'

//If it's somewhere in the string:

(" Hello 123 World4").replace( /(^.+)(\w\d+\w)(.+$)/i,'$2'); //=> '123'

//And for a number between characters:

("Hello123World 4").replace( /(^.+\D)(\d+)(\D.+$)/i,'$2'); /=> '123''

Good stuff!