Home >Web Front-end >JS Tutorial >How to Create a Regex for Alphanumeric Strings in JavaScript?
Creating a RegEx for Alphanumeric Only Strings in JavaScript
When crafting a RegEx pattern to validate alphanumeric strings, it's essential to consider scenarios where the string may contain only letters or only numbers. To cater to this requirement, we can craft a pattern that allows either type of character without mandating both.
To accomplish this, we can utilize the following RegEx expression:
/^[a-z0-9]+$/i
Breaking down the pattern:
Example Usage
Consider the following code snippet:
const inputString = "abc123"; const isAlphanumeric = /^[a-z0-9]+$/i.test(inputString); console.log(isAlphanumeric); // Output: true
In this example, the inputString contains only alphanumeric characters, and thus it passes the RegEx validation, resulting in a true output.
Supporting Universal Characters
If the requirement is to support universal characters, including languages like Persian or Arabic, we can modify the pattern as follows:
/^([a-zA-Z0-9\u0600-\u06FF\u0660-\u0669\u06F0-\u06F9 _.-]+)$/
This updated pattern includes character ranges for Persian characters, allowing the RegEx to validate strings containing Persian characters.
The above is the detailed content of How to Create a Regex for Alphanumeric Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!