Am I being dense, or do boundaries seem to break the matching of hyphens in JavaScript regular expressions?
var string1 = "example words";
/\bexample\b/.test(string1); // true (all good)
var string2 = "-example -words";
/\b-example\b/.test(string2); // false (confusion)
Maybe I've misinterpreted the boundary behaviour?
Escaping the hyphen doesn't seem to help either...
It is because \b is word boundary and - or hyphen is already considered a non word character. You can use this regex insstead:
/-example\b/.test('-example -words');
true
The issue is that - is not a "word character". \b matches the boundary between a word character and a non-word character. The space before the - does not match this definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With