Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions with Hyphens seem broken when using Boundaries?

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...

like image 914
shennan Avatar asked Dec 12 '25 17:12

shennan


2 Answers

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
like image 168
anubhava Avatar answered Dec 15 '25 08:12

anubhava


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.

like image 43
James Montagne Avatar answered Dec 15 '25 10:12

James Montagne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!