Transcript
[00:00] When we wanna find a whole word in regular expression, there are a whole bunch of different ways to do it. But one really handy way to do it is called word boundaries. So I’ve got this sentence here. This is his island history.
[00:13] And we can see that the pattern lowercase i followed by lowercase s appears a bunch. So we’re gonna capture that first. And obviously we’re not getting just the word is, we’re getting every instance of is. We could try to get clever and use like a look ahead, say it’s gonna be followed by a space. And it’s kind of close. I don’t know, that’s not really gonna work. So let’s back up here a second. What we’re gonna do is we’re gonna use word boundaries. And we can do that with a forward slash and then a lowercase b.
[00:48] And this being at the beginning of the string says, this is a word that begins with i s. And I do that and I get is, but I also get island. So if I just want is, I just have to go to the end and say, this is the boundary at the end of the word. So this word begins with this pattern i s and ends with this pattern i s. And there you go, we got our word.
[01:12] Now we can also negate that. So let’s say, I wanna say it’s a word that does not begin with i s, but it does have that pattern. Cool, we get this and his and history. But let’s say we just want history. So we want a word that contains i s, but does not begin and end with i s. And there you go, we have history. And that’s all there is to it with word boundaries.
Word boundaries help you match whole words rather than substrings. This lesson covers the \b anchor, which matches at the boundary between a word character and a non-word character. You’ll see how to match a specific word (“is”) without matching it inside words like “island” or “history.” We also cover negated word boundaries (\B) for matching patterns that are NOT at word boundaries — useful for finding words containing a pattern but not starting or ending with it.
app.js
import output from "./output.js";
let str = `This is his island history`;
let regex = /is/g;regex = /is(?=\s)/g;regex = /is(?=\s)?/g;regex = /\bis/g;regex = /\bis\b/g;regex = /\Bis/g;regex = /is\B/g;regex = /\Bis\B/g;
output(str, regex);