JavaScript \0 Metacharacter: RegEx Search Null Character

The JavaScript \0 metacharacter is used to find a null character in a string using JavaScript regular expressions. For example:

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

  <p id="myPara"></p>

   <script>
      let myString = "JavaScript is Fun.\0Is not it?";
      let pattern = /\0/;
      document.getElementById("myPara").innerHTML = myString.search(pattern);
   </script>
   
</body>
</html>
Output

Since the \0 is available at index number 18, the above JavaScript code produces 18 as output.

Note: The search() method is used to search for a substring (value) in a string using a regular expression.

The "\0" RegEx metacharacter in JavaScript is used in the above example to search for the null character in a string. The null character, represented by the escape sequence \0 or the Unicode character code U+0000, is a non-printable control character.

In this case, the myString variable is set to the string "JavaScript is Fun.\0Isn't it?" with a null character at the 16th index. The "pattern" variable is initialized with a regular expression that uses the \0 metacharacter to match the null character.

The string object's search() method is then called on the myString variable with the pattern variable as an argument. In this case, the search() method returns the index of the first occurrence of the pattern in the string, which is 16.

Finally, the innerHTML property of the paragraph element with ID "myPara" is set to the returned index value, resulting in "16" being displayed on the web page.

Now, before we wrap up our discussion of the "\0" metacharacter in JavaScript RegEx, I'd like to include one more example with a proper comment to explain each line of code in the program itself:

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

   <script>
      // Initialize a string variable containing a null character
      let myString = "This string contains a null character at position 5.\0The rest of the string is ignored.";

      // Create a regular expression to match the null character
      let pattern = /\0/;

      // Use the search() method to find the index of the first occurrence of the null character in the string
      let nullIndex = myString.search(pattern);

      // Output the index of the null character to the console
      console.log("The null character is at index " + nullIndex);
   </script>
  
</body>
</html>
Output
The null character is at index 52

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!