Hi Friends 👋,
Welcome To Infinitbility! ❤️
To validate alphabets only string using regex, use /^[a-zA-Z]+$/
it will handle all alphabates only.
Let’s see short example of javascript regex for alphabets only.
const regex = /^[a-zA-Z]+$/;
console.log(regex.test("hello"))
Today, I’m going to show you How do I check value contain only alphabets in javascript, as above mentioned, I’m going to use the above-mentioned regex with test()
method.
Let’s start today’s tutorial how do you allow only alphabets in javascript using regex?
Here, I will show allow only alphabets in javascript and typescript.
Javascript regex allow only alphabets example
Here, we will create common validate function where we will validate param should alphabates only.
function validate(param){
const regex = /^[a-zA-Z]+$/;
return regex.test(param);
}
// validate empty
console.log(validate(""))
// false
// validate string
console.log(validate("INFINIT"))
// true
// validate number
console.log(validate("8954"))
// false
// validate words with space
console.log(validate("infinit bility"))
// false
// validate words with hyphen
console.log(validate("infinit-bility"))
// false
Output
Typescript regex allow only alphabets example
Same like javascript, we will create a function and call it with diffrent parameters.
function validate(param: string){
const regex = /^[a-zA-Z]+$/;
return regex.test(param);
}
// validate empty
console.log(validate(""))
// false
// validate string
console.log(validate("INFINIT"))
// true
// validate number
console.log(validate("8954"))
// false
// validate words with space
console.log(validate("infinit bility"))
// false
// validate words with hyphen
console.log(validate("infinit-bility"))
// false
Output
I hope it helps you, All the best 👍.