Eli
Eli

Reputation: 4359

how to select a dynamic string from a sentence

How can I select the first number from these example sentences

"  1     SAMPLE SAMPLE 1"
"  20     SAMPLE SAMPLE 2"

I want to isolate the first number from those lines.

I tried a few string functions that come with javascript but can't seem to make them work. I don't want the spaces, I need the number only.

Upvotes: 1

Views: 118

Answers (2)

generalhenry
generalhenry

Reputation: 17319

var num = "  1     SAMPLE SAMPLE 1".match(/^\s*?(\d).*?$/)[1];

Upvotes: 0

user113716
user113716

Reputation: 322602

This should do it.

var num = +/\d+/.exec("  1     SAMPLE SAMPLE 1")[0];

If you didn't need it converted to a number, then you can get rid of the first +.

var num = /\d+/.exec("  1     SAMPLE SAMPLE 1")[0];

If you're not certain if there'll be a number, you'll want to get rid of the [0], and extract the result after verifying.

var num = /\d+/.exec("       SAMPLE SAMPLE ");

if( num ) num = num[0];

Or since it's a number, you could convert it with + right from the Array.

if( num ) num = +num;

Upvotes: 3

Related Questions