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
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
I think this would work:
var matches = "MIN20, MAX40".match(/MIN(\d+), MAX(\d+)/);
var min = matches[1];
var max = matches[2];
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]
var str = "MIN20, MAX40";
value = str.replace(/^MIN(\d+),\sMAX(\d+)$/, function(s, min, max) {
return [min, max]
});
console.log(value); // array
This should do the trick.
var str='MIN20, MAX40';
min = str.match(/MIN(\d+),/)[1];
max = str.match(/MAX(\d+)$/)[1];
精彩评论