JavaScript RegExp – \r

JavaScript RegExp – \r

If you are someone who works with strings in JavaScript, you probably know about Regular Expressions, commonly known as RegEx. RegEx is a pattern that is used to match characters in a string. It’s a powerful tool that can be used for various purposes like validation, searching, and replacing strings. In this article, we will discuss one of the RegEx characters – \r.

What is \r?

The \r character is used to match a carriage return character in a string. In most programming languages, a carriage return is represented by the escape sequence \r. It’s used to move the cursor to the beginning of a new line. For example, when you press the “Enter” key on your keyboard, it generates a carriage return character which is then interpreted as a new line in your document.

Example usage of \r

Let’s look at an example of how we can use the \r character in a Regular Expression. Suppose you have a string like “Hello\rWorld”. Here, \r is used to indicate that the cursor should return to the beginning of the line. If we want to match this character in our RegEx, we can use the following code:

const string = "Hello\rWorld";
const regExp = /\r/g;
string.match(regExp); // Returns ["\r"]

Here, we are using the match() method to search for the \r character in our string. The g flag is used to ensure a global search, which means we search for all occurrences of the \r character in the string.

Other uses of \r

Apart from its usage in RegEx, the \r character is also used in other places like text editors and word processors. It’s used to indicate the start of a new line within a paragraph or a block of text.

Conclusion

The \r character is a useful tool in JavaScript RegEx, as it allows us to match the carriage return character in a string. It’s important to use it correctly, and to keep in mind that it’s just one of the many RegEx characters available. By learning RegEx, you can become more proficient in working with strings in JavaScript, and make your code more efficient and effective.

Like(0)