JavaScript RegExp – [^…]

JavaScript RegExp – [^...]

When it comes to working with strings in JavaScript, regular expressions (RegEx) are an essential tool. They allow us to search for patterns within a string, replace parts of the string, and much more. One of the most useful and commonly used features of RegEx is negating characters using the [^…] syntax.

What is [^...] in RegEx?

The syntax [^...] within a regular expression allows us to match any character that is not within the specified set. For example, the regular expression [^aeiou] will match any character that is not a vowel. Let’s look at some sample code to understand it better:

let str = "The quick brown fox jumps over the lazy dog.";
let nonVowelsRegEx = /[^aeiou]/g;
let nonVowels = str.match(nonVowelsRegEx);
console.log(nonVowels);

In this code snippet, the string str is searched for any characters that are not vowels. The regular expression used is /[^aeiou]/g, which matches any character that is not a vowel. The g flag is used to search for all occurrences of the pattern within the string. The output of this code will be an array of all the non-vowel characters in the string:

["T", "h", " ", "q", "c", "k", " ", "b", "r", "w", "n", " ", "f", "x", " ", "j", "m", "p", "s", " ", "v", "r", " ", "t", "h", " ", "l", "z", "y", " ", "d", "g", "."]

Using [^…] with other RegEx characters

The [^…] syntax can be combined with other RegEx characters to create more complex patterns. For example, let’s say we want to match any character that is not a vowel, but only if it is followed by the letter r. The regular expression for this would be /[^aeiou]r/g. Let’s look at some sample code:

let str = "The quick brown fox jumps over the lazy dog.";
let nonVowelsFollowedByRRegEx = /[^aeiou]r/g;
let nonVowelsFollowedByR = str.match(nonVowelsFollowedByRRegEx);
console.log(nonVowelsFollowedByR);

In this code snippet, the regular expression /[^aeiou]r/g is used to match any non-vowel character followed by the letter r. The output of this code would be an array containing the matches:

["cr"]

Conclusion

In this article, we have discussed the syntax [...] in regular expressions, which allows us to match any character that is not within the specified set. We have also seen how this syntax can be combined with other RegEx characters to create more complex patterns. The [...] syntax is a powerful tool for working with strings in JavaScript, and can be used in many different ways to solve a wide range of problems.

Like(0)