8

If you are given a string like "foo bar 32536364" and a regex /foo bar \d+/, how can you check if the regex matches the full string and not some substring in the string? Also I cannot change the input values such as putting ^ and $.

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474
  • Check to see if the matched string is the same length as the source string? – Pointy May 01 '18 at 14:18
  • Exactly. [`var m = rx.exec(s); if (m && m[0].length === s.length) { console.log("Full match!") } else { console.log("No match!") }`](https://jsfiddle.net/2e3xbes5/) – Wiktor Stribiżew May 01 '18 at 14:22

1 Answers1

14

You can either compare the length of the source to the match or compare the matched string to the source, if they are the same, you matched the entire string, and not just a part of it:

let source1 = "foo bar 12345";
let source2 = "foo bar 12345 foo";

let match1 = source1.match(/foo bar \d+/);
let match2 = source2.match(/foo bar \d+/);

console.log(match1[0] === source1);
console.log(match1[0].length === source1.length);

console.log(match2[0] === source2);
console.log(match2[0].length === source2.length);
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44