0

In a javascript code want to match a string with regex to return boolean (if string meets the requirement).

The string should end with yes, no, or maybe non-case-sensitive and can be wrapped with (or only at one side) a double-quote. so any string that ends with "Yes", "yes", yes, "YES", etc. is acceptable.

I have the following which is wrong. How should I construct the regex, or is it a good way in javascript?

function test(){
var str =document.getElementById("str").value;  
const regex = /.*\"?[YES|NO|MAYBE]\"?$/gmi;
const result = new RegExp(regex).test(str);
console.log(result);
}
<input type="text" id="str" name="str" value=""/>
<input type="button" value="test" onclick="test()"/>  
Amir-Mousavi
  • 4,273
  • 12
  • 70
  • 123
  • 1
    `[...]` is a character class, you need a grouping construct, `(...)` / `(?:...)`. `const regex = /"?(?:YES|NO|MAYBE)"?$/i` or `const regex = /(?:"(?:YES|NO|MAYBE)"|YES|NO|MAYBE)$/i` – Wiktor Stribiżew Jun 11 '20 at 14:57
  • @WiktorStribiżew Sorry by that I meant etc – Amir-Mousavi Jun 11 '20 at 14:59
  • 1
    I see, but the main problem is still that you are using `[...]`, which is a character class. Note you [should avoid](https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results) `g` flag in patterns that you use in `RegExp#test` – Wiktor Stribiżew Jun 11 '20 at 15:00
  • @WiktorStribiżew Thanks a lot – Amir-Mousavi Jun 11 '20 at 15:02

0 Answers0