JavaScript RegExp – \v

JavaScript RegExp – \v

JavaScript is a powerful programming language that supports a wide range of operations. One of the most important operations in JavaScript is pattern matching or searching. And to perform pattern matching in JavaScript, we use Regular Expressions, commonly known as Regex. Regex is a powerful tool that allows us to search, replace, and manipulate text data in JavaScript.

In this article, we’ll discuss one of the most useful features of Regex – the \v character.

What is \v?

The \v character is a special character in JavaScript’s Regex syntax that matches any vertical whitespace character. Vertical whitespace characters include characters such as the newline character (\n), form feed (\f), vertical tab (\v), carriage return (\r), and the Unicode characters “\u000B”, “\u000C”, and “\u2028”.

The \v character is quite similar to the \s character, which matches any whitespace character, including spaces, tabs, and line breaks. However, the \v character only matches vertical whitespace and doesn’t include spaces or tabs.

To use the \v character in JavaScript’s regex, we need to include it inside a pair of forward slashes, like this:

const regex = /Hello\vWorld/;

This regex pattern will match any text that contains the string “Hello”, followed by a vertical whitespace character, and then the string “World”.

Here’s an example of how the \v character can help you extract data from a CSV file that contains vertical whitespace characters:

const csvData = "John,Doe,26\nRita,Smith,24\vAlex,Garcia,31\n";

const regex = /([^,\n\v]+),([^,\n\v]+),(\d+)/g;

let match;
while ((match = regex.exec(csvData))) {
  console.log(`Full match: {match[0]}`);
  console.log(`First name:{match[1]}`);
  console.log(`Last name: {match[2]}`);
  console.log(`Age:{match[3]}`);
  console.log("-----------------------------");
}

This regex pattern will match each record in the CSV data and extract the first name, last name, and age. The vertical whitespace character between the second and third record will also be considered as a record separator and properly handled.

Conclusion

The \v character is a powerful tool in JavaScript’s regex syntax that allows us to match vertical whitespace characters. We can use it to perform complex pattern matching and data extraction tasks. If you want to learn more about using Regex in JavaScript, there are many online resources available. With the \v character in our toolkit, we can confidently search and manipulate text data in JavaScript.

Like(0)