This code detects if a regular expression is in a string, and returns them as a JSON string
According to the code, the code does not support for any regex starting with special characters such as (#,@..etc). If i call the function js_regex(#3[0-9]{2},"#312 hyderabad") , #312 is not getting returned as a rslt, whereas if I call js_regex(3[0-9]{2},"312 hyderabad") , 312 is getting returned as rslt
How do I support the patterns for special characters also in the below code?
function js_regex(expr, str) {
var rslt = "";
// extract any specific flags
var flags = "gi";
if (expr.startsWith("/")) {
var exprend = expr.length - 1;
if (!expr.endsWith("/")) {
exprend = expr.lastIndexOf("/");
flags = expr.substring(exprend + 1);
}
expr = expr.substring(1, exprend);
}
if (expr.length === 0) {
return rslt;
}
// only interested in words
expr = "\\b" + expr + "\\b";
// run the regex, and save the results as a JSON string
var re = new RegExp(expr, flags);
var matches = str.match(re);
if (matches) {
rslt = JSON.stringify(matches);
}
return rslt;
};
console.log(js_regex("#3[0-9]{2}", "#312 hyderabad"))
console.log(js_regex("3[0-9]{2}", "312 hyderabad"))
expr = "\\b" + expr + "\\b";must be something likeexpr = "(?:^|\\W)(" + expr.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + ")(?!\\w)"; var matches =[];and then usewhile(m=re.exec(str)) { matches.push(m[1]); }