I really have difficulty setting up regular expressions, mainly for varying their behavior in each language. I'm translating a Java code into JS, in which the regular expression is /(\d{1,4}|\*)\s*[xX]\s*(\d{1,4}|\*)/
, so I understand it captures any number (size from 1 to 4 characters) that have at least the X or x separating from another set of numbers.
My question is: Why can not I capture "1024x768 px until 1920x1080" so I can match also in "1920x1080"?
JS
function process(val) {
if (val != null) {
val = val.replace("X", "x");
val = val.replace(/ /g, "");
const DIMENSAO_UNIT = "px";
const DIMENSAO_PATTERN = /(\d{1,4}|\*)\s*[xX]\s*(\d{1,4}|\*)/;
var normalizado = val.trim().toLowerCase().replace(DIMENSAO_UNIT, "");
var valores = [];
var out = "";
if (DIMENSAO_PATTERN.test(val)) {
var getNumbers = val.match(DIMENSAO_PATTERN);
var i = 0;
for (i = 0; i < getNumbers.length; i++) {
valores.push(getNumbers[i]);
}
}
if(val == ""){
return "";
}
if (normalizado.indexOf("superior") > -1) {
return valores[0] + DIMENSAO_UNIT + " ou superior";
} else if (normalizado.indexOf("até") > -1) {
if (valores.length == 1) {
out = "até " + valores[0];
} else {
out = valores[0] + " até " + valores[1];
}
} else if (normalizado.indexOf("ou") > -1 || normalizado.indexOf("/") > -1) {
out = valores[0];
var j = 0;
for (j = 1; j < valores.length; j++) {
out = "/" + valores[j];
}
} else {
if (valores.length > 0) {
out = valores[0];
}
}
if (out !== null || out !== "") {
return out + DIMENSAO_UNIT;
}
return "";
}
return null;
}
** UPDATE: I just needed to add the global (g): /(\d{1,4}|\*)\s*[xX]\s*(\d{1,4}|\*)/g
but leave open p explanations