Dovydas
Dovydas

Reputation: 233

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);
}

Upvotes: 1

Views: 148

Answers (2)

Joe
Joe

Reputation: 1696

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>");

Upvotes: 1

vks
vks

Reputation: 67968

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>');

Upvotes: 6

Related Questions