views:

947

answers:

4

I have a string in a loop and for every loop it is filled with texts the looks like this:

"123 hello everybody 4" "4567 stuff is fun 67" "12368 more stuff"

I only want to retrieve the first numbers up to the text in the string and I ofcourse do not know the length.

Thanks in advance!

+1  A: 

If you want an int, just parseInt(myString, 10). (The 10 signifies base 10; otherwise, JavaScript may try to use a different base such as 8 or 16.)

Ben Alpert
+4  A: 
var str = "some text and 856 numbers 2";
var match = str.match(/\d+/);
document.writlen(parseInt(match[0], 10));

If the strings starts with number (maybe preceded by the whitespace), simple parseInt(str, 10) is enough. parseInt will skip leading whitespace. 10 is necessary, because otherwise string like 08 will be converted to 0 (parseInt in most implementations consider numbers starting with 0 as octal).

Eugene Morozov
A: 

Use Regular Expressions:

var re = new RegExp(/^\d+/); //starts with digit, one or more
var m = re.exec("4567 stuff is fun 67");
alert(m[0]); //4567

m = re.exec("stuff is fun 67");
alert(m); // null
Spikolynn
A: 

If the number is at the start of the string:

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

If it's somewhere in the string:

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

And for a number between characters:

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