Home > Blockchain >  How to create a JS collection of characters regex?
How to create a JS collection of characters regex?

Time:12-17

How to create a JS collection of characters regex?

E.g. I want to allow a string to contain any characters from the string: ÀàÂâĂăÄä. Here is what I am trying to do: "^[ÀàÂâĂăÄä] $".

But the regex does not recognize even the first letter only, i.e. the À. What am I missing here?

Here is the regex test attempt. I am trying to match the Àààààà against the regex.

CodePudding user response:

To create a regular expression that matches a string containing any character from a specific set of characters, you can use a character class. A character class is a set of characters inside square brackets ([]). For example, the regular expression [abc], will match any single character that is either a, b, or c.

In your case, you can use the following regular expression to match a string containing any of the characters in the string ÀàÂâĂăÄä:

/^[ÀàÂâĂăÄä] $/

Here's an example of how you can use this regular expression to test if a string contains only characters from the specified set:

const regex = /^[ÀàÂâĂăÄä] $/;
const str = 'Àààààà';

console.log(regex.test(str)); 

If you want to match any character from a set of characters that includes characters with special meaning in regular expressions (such as [,],-,^, or \), you can use a backslash to escape these characters. For example, the regular expression [\[\]\\^-] will match any of the characters [,], \, ^, or-.

  • Related