Ask Your Question
4

How can we exclude specific characters within [] in JavaScript Regex?

asked 2023-07-05 21:52:48 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-05 22:10:02 +0000

david gravatar image

To exclude specific characters within [], use the caret (^) symbol immediately after the opening bracket. For example, to match any lowercase letter except for the letter "e", you can use the regex [a-df-z].

Here is an example:

const text = "The quick brown fox jumped over the lazy dog.";
const regex = /[^aeiou]/g;

const result = text.match(regex);
console.log(result); // Output: ["T", "h", " ", "q", "c", "k", " ", "b", "r", "w", "n", " ", "f", "x", " ", "j", "m", "p", "d", " ", "v", "r", " ", "t", "h", " ", "l", "z", "y", " ", "d", "g", "."]

In the example above, the regex /[^aeiou]/g matches any character that is not a vowel. The ^ symbol inside the square brackets means "not", so it excludes the characters a, e, i, o, and u. The resulting result array contains all the non-vowel characters in the text string.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-05 21:52:48 +0000

Seen: 13 times

Last updated: Jul 05 '23