Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript Regex question mark (?) not detect [duplicate]

Hi all I tried to create some regex with random value.

var data = "demo purpose?";  **OR**  var data = "demo purpose";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp("\\b(" + data + ")\\b", "g");
console.log(sentence.match(re));   // output ["demo purpose"]

In variable data have two different value demo purpose? & demo purpose with only question mark. Both console out are same please any one Give me hint what should i do in these case.

- Thank you

like image 421
Gunjan Patel Avatar asked Apr 19 '26 06:04

Gunjan Patel


2 Answers

you need to escape ? (i.e. write \\?) or else it would be interpreted as a quantifier in regex.

Furthermore, the \\b is not really necessary because it tries to match a non blank char in which case there is nothing behind demo purpose? so sentence.match(new RegExp("\\b(demo purpose\\?)\\b", "g")) would return null.

If you want randomness, use Math.random. Make an array and get an random integer or 0 or 1 (with Math.floor) as the index.

like image 182
Archy Will He 何魏奇 Avatar answered Apr 21 '26 20:04

Archy Will He 何魏奇


In order to pass variables into JS regex when using constructor notation, you need to escape all characters that act as regex special characters (quantifiers, group delimiters, etc.).

For older JS environments, you may use this escaping function :

function escapeRegExp(string){
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

For the latest JavaScript environments, you may use RegExp.escape function.

Note also, that \b is a word boundary, and it prevents from matching the strings you need as ? is a non-word character. If you do not need to match word boundaries, remove \b. If you need to check if the search word is a whole word, use (?:^|\W) at the beginning and (?!\w) at the end and use exec rather than match to obtain access to the captured group 1.

So, your code will become:

function escapeRegExp(string){
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

var data = "demo purpose?";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp("(?:^|\\W)(" + escapeRegExp(data) + ")(?!\\w)", "g");
while ((m = re.exec(sentence)) !== null) {
   console.log(m[1]);   // output ["demo purpose?"]
}

If you search for emo purpose?, no result will be returned since there will be no match.

Also, consider using adaptive word boundaries:

const data = "demo purpose?";
const sentence = "can I put these app as demo purpose?";
const re = new RegExp(String.raw`(?!\B\w)${RegExp.escape(data)}(?!\B\w)`, "g");
console.log(Array.from(sentence.matchAll(re), (x) => x[0]));   // output ["demo purpose?"]
like image 21
Wiktor Stribiżew Avatar answered Apr 21 '26 20:04

Wiktor Stribiżew