Tom
Tom

Reputation: 93

JavaScript Regular Expression - Extract number from next to word

Been a long time since I have touched regular expressions. It's simple but I am pulling my hair out over it.

I have a string as follows that I get from the DOM "MIN20, MAX40". I want to be able to use regex in JavaScript to extract the integer next to MIN and the integer next to MAX and put into separate variables min and max. I cannot figure a way to do it.

Thanks to who ever helps me, you will be a life saver!

Cheers

Upvotes: 9

Views: 20978

Answers (5)

codaddict
codaddict

Reputation: 455042

You can use:

var input   = "MIN20, MAX40";
var matches = input.match(/MIN(\d+),\s*MAX(\d+)/);
var min = matches[1];
var max = matches[2];

JSfiddle link

Upvotes: 18

user69820
user69820

Reputation:

I think this would work:

var matches = "MIN20, MAX40".match(/MIN(\d+), MAX(\d+)/);
var min = matches[1]; 
var max = matches[2];

Upvotes: 4

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

This should do the trick.

var str='MIN20, MAX40';

min = str.match(/MIN(\d+),/)[1];
max = str.match(/MAX(\d+)$/)[1];

Upvotes: 0

Tim Down
Tim Down

Reputation: 324577

The following will extract numbers following "MIN" and "MAX" into arrays of integers called mins and maxes:

var mins = [], maxes = [], result, arr, num;
var str = "MIN20, MAX40, MIN50";

while ( (result = /(MIN|MAX)(\d+)/g.exec(str)) ) {
    arr = (result[1] == "MIN") ? mins : maxes; 
    num = parseInt(result[2]);
    arr.push(num);
}

// mins: [20, 50]
// maxes: [40]

Upvotes: 2

fcalderan
fcalderan

Reputation:

var str = "MIN20, MAX40";
value = str.replace(/^MIN(\d+),\sMAX(\d+)$/, function(s, min, max) {
    return [min, max]
});

console.log(value); // array

Upvotes: 0

Related Questions