简体   繁体   中英

Regular expression, pick first numbers from string

I have a string

var str = "14⊰Ⓟ⊱ 7⊰➆Ⓑ⊱ 12⊰Ⓢ⊱ 7⊰➆Ⓑ⊱"; 

and I need to pick first numbers in string(14, 7, 12, 7).

I wrote code the following code, but this code picks numbers separated (1, 4, 7, 1, 2, 7):

for (var i = 0; i < str.length; i++) {
    newStr = str.match(/\d/g);
}

The problem with your regex is that it is missing + quantifier after \\d . \\d will match only one number.

You can use \\d+ to match all numbers. The + quantifier will match one or more of the previous class.

Alternately, you can also use [0-9]+ .

Regex101 Demo

 var str = '14⊰Ⓟ⊱ 7⊰➆Ⓑ⊱ 12⊰Ⓢ⊱ 7⊰➆Ⓑ⊱'; var matches = str.match(/\\d+/g); console.log(matches); document.write('<pre>' + JSON.stringify(matches, 0, 4) + '</pre>'); 

That loop looks redundant, unless you omitted something from copypaste. String object's match method returns an array, not a string.

var numbers = str.match(/\d+/g);

Gives you a following array: ["14", "7", "12", "7"] .

You may further cast matches to integers by:

numbers = numbers.map(function(n) { return parseInt(n); });

Example

 var str = "14⊰Ⓟ⊱ 7⊰➆Ⓑ⊱ 12⊰Ⓢ⊱ 7⊰➆Ⓑ⊱"; var numbers = str.match(/\\d+/g).map(function(n) { return parseInt(n); }); // or as Tushar pointed out: var numbers = str.match(/\\d+/g).map(Number); document.write("<pre>" + JSON.stringify(numbers) + "</pre>"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM