/\Bon/
matches "on" in "at noon", and /ye\B/
matches "ye" in
"possibly yesterday". Why does this happen?
That is the correct and expected behavior:
console.log("at noon".match(/\Bon/)[0]);
console.log("possibly yesterday".match(/ye\B/)[0]);
Unlike character classes like \w
, which match a single "word" character, or \s
that matches a single white space character, \B
is anchor point it does not match a character, it instead asserts that that anchor is at a specific place. In the case of \B
, it asserts that that anchor is not at a word boundary.
A word boundary would either be a place where a "word character" is next to a white space character or the beginning or end of the string.
So, /\Bon/
effectively means find an "on" that is not at the start of a word. That is why the "on" in "noon" matches; but something like the "on" in "at one" does not:
console.log("at one".match(/\Bon/));
In the same way, /ye\B/
effectively means find a "ye" that is not at the end of a word. So, the "ye" in "possibly yesterday" matches because it is not at the end of the word, whereas the "ye" at the end of "possibly goodbye" does not:
console.log("possibly goodbye".match(/ye\B/));
It should also be added that \B
should not be confused with \b
, they have different meanings. \b
matches an anchor point at a word boundary. So, if you wanted to find a word that starts with "on" you could use /\bon/
:
console.log("one at noon".match(/\bon/)); // finds the "on" in one, but not the "on" in noon
Likewise it can be used to find something at the end of a word:
console.log("goodbye yesterday".match(/ye\b/)); // finds the "ye" in goodbye, but not the "ye" in yesterday