Reputation:
I'm learning regular expressions in JavaScript and the problem I am facing is i'm trying to understand why the \b meta character is so special to use? I see no difference by not using it vs using it so what is the difference between using it and not using it? This is what I mean.
WITH \b
<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search for "W3" at the beginning or end of a word in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools";
var patt1 = /\bW3/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
WITH OUT \b
<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search for "W3" at the beginning or end of a word in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools";
var patt1 = /W3/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
I already know what it means by definition by reading it but i'm simply just questioning why use it if it produce the same thing in the above 2 code examples? If any one can show me 2 code examples to show how they will give different results I will really appreciate that. I even move the match in the middle but it still gave me the same result as with out using it.
SOURCE
https://www.w3schools.com/jsref/jsref_regexp_begin.asp
Upvotes: 2
Views: 57
Reputation: 487
\b means a "word-break" character (listed here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions -> http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.2.6)
var str = "aaaé";
var patt = /\baaa\b/;
var result = str.match(patt); /* match it */
but
var str = "aaab";
var patt = /\baaa\b/;
var result = str.match(patt); /* doesnt match it */
Upvotes: 0
Reputation: 2981
Both of your examples fail to do what the html claims they are going to do. Go to https://www.regextester.com/ and use blahW3blah
, W3blah
, and blahW3
as your test strings. Your regex should match the last two, but not the first.
You need:
(\bW3|W3\b)
(Match W3 at the beginning of a word (\bW3
) OR (|
) match W3 at the end of a word (W3\b
)
Upvotes: 2