开发者

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 w开发者_运维技巧ork. I don't want the spaces, I need the number only.


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;


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜