-3
const str = 'Submission Date (Expected)';

const regex = new RegExp("^" + str + "$")

console.log(regex.test(str));

Output: FALSE

I'm using this site for testing: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

The goal is to compare string, EXACT MATCH. When I remove brackets from const str it returns TRUE but i need TRUE with brackets.

I tried this but it doesn't work

const str = 'Submission Date \(Expected\)';
user3590094
  • 119
  • 1
  • 2
  • 11
  • Use the function mentioned in the [duplicate](https://stackoverflow.com/a/3561711/3082296). If you want to make the literal work as is, you need two slashes `\\(Expected\\)` – adiga Apr 22 '21 at 09:44
  • @adiga i tried this , still same OUTPUT – user3590094 Apr 22 '21 at 09:49
  • If `str` is the escaped string, test it against `'Submission Date (Expected)'` not against `str` again. – adiga Apr 22 '21 at 09:50

1 Answers1

0

Before using a bare string within regex, you need to escape it like explained in this question: Is there a RegExp.escape function in JavaScript?

René Jahn
  • 1,155
  • 1
  • 10
  • 27
  • I did const str1 = escapeRegex(str) and console.log(regex.test(str1)); , still same output – user3590094 Apr 22 '21 at 09:46
  • @user3590094 Works fine: `const str = 'Submission Date (Expected)', str1 = escapeRegex(str), regex = new RegExp("^" + str1 + "$"); console.log(regex.test(str));` – adiga Apr 22 '21 at 09:54