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

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

The \b Metacharacter

The \b metacharacter is used when we need to match any word based on the pattern beginning or ending with 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 above program has produced Ja two times.

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

Note: The match() method is used to match a string with/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 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

Unlike \b, the \B metacharacter is used when we need to match those words that does not begins or ends with 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 starts with 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 »



Like/Share Us on Facebook 😋