Seperate a number (int) from string using Mootools

Posted in Javascript | No Comments
I recently blogged about using regular expressions to extract a number or integer from a string in javascript. So what if you are using Mootools? Well you save even more time:
//only works for a string beginning with a number!
('123 Hello World').toInt();  //=> '123'
Mootools FTW! Tags:

Seperate a number (int) from a string in Javascript

Posted in Javascript | No Comments
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!