JavaScript \b and \B Metacharacters: What is b in RegEx?

This post is published to provide information about two metacharacters used in JavaScript regular expressions. That are:

The \b metacharacter in JavaScript

The \b metacharacter is used when we need to match any word based on the pattern beginning or ending with a specified character or combination of characters. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "JavaScript and Java are Fun to Learn.";
      let pattern = /\bJa/g;
      document.getElementById("xyz").innerHTML = myString.match(pattern);
   </script>
   
</body>
</html>
Output

Since there are two words that are JavaScript and Java, which starts with Ja, therefore, the above program has produced Ja twice.

The g (from /\bJa/g) used in the above example forces the match pattern to go globally. It means the search does not stop after getting the first match; rather, it matches the whole string.

Note: The match() method is used to match a string with or using a regular expression.

Here is another example demonstrating how we can use the \b metacharacter to match the end of words:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>
   
   <script>
      let myString = "JavaScript and Java are Fun to Learn.";
      let pattern = /va\b/g;
      document.getElementById("abc").innerHTML = myString.match(pattern);
   </script>
   
</body>
</html>
Output

Since there is only one word ending with va, that is Java. Therefore, the output produced by the above program is va for only one time.

Let me create one last example that matches all words starting with a:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="myPara"></p>
   
   <script>
      let myString = "JavaScript and Java are Fun to Learn.";
      let pattern = /\ba/g;
      document.getElementById("myPara").innerHTML = myString.match(pattern);
   </script>
   
</body>
</html>
Output

The \B metacharacter in JavaScript

Unlike \b, the \B metacharacter is used when we need to match those words that do not begin or end with a specified character or combination of characters. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="mp"></p>

   <script>
      let myString = "JavaScript and Java are Fun to Learn.";
      let pattern = /\Ba/g;
      document.getElementById("mp").innerHTML = myString.match(pattern);
   </script>
   
</body>
</html>
Output

Since there are five words in the string "JavaScript and Java are Fun to Learn," which does not start with a specified character, that is a, therefore, the program produced "a" five times. Those five words are: JavaScript, Java, Fun, to, and Learn.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this article? Share it!



Like/follow us on social media for updates!