Sok Chanty
Sok Chanty

Reputation: 1816

JS - regx allow only alphanumeric

I'm looking for alphanumeric regex expression that allow only alphabets. I have tried with this this code

^[a-zA-Z0-9]+$

But, it seem not work correctly. I'm looking for regex that allow only string below.

const str1 = 78;
const str2 = 'contains spaces';
const str3 = 'with symbols !@#$%^&';
const str4 = 'user78';
const str4 = 'khemvesna';

function alphanumeric(str) {
  const regx = /^[a-zA-Z0-9]+$/;
  return regx.test(str);
}

console.log(alphanumeric(str1)); // 👉️ false
console.log(alphanumeric(str2)); // 👉️ false
console.log(alphanumeric(str3)); // 👉️ false
console.log(alphanumeric(str4)); // 👉️ true
console.log(alphanumeric(str5)); // 👉️ true

Upvotes: 0

Views: 95

Answers (1)

Richard Henage
Richard Henage

Reputation: 1808

To only match strings that contain at least one letter, and contain nothing other than letters/numbers:
^[a-zA-Z0-9]*[a-zA-Z][a-zA-Z0-9]*$

const str1 = 78;
const str2 = 'contains spaces';
const str3 = 'with symbols !@#$%^&';
const str4 = 'user78';
const str5 = 'khemvesna';

function alphanumeric(str) {
  const regx = /^[a-zA-Z0-9]*[a-zA-Z][a-zA-Z0-9]*$/;
  return regx.test(str);
}

console.log(alphanumeric(str1)); // 👉️ false
console.log(alphanumeric(str2)); // 👉️ false
console.log(alphanumeric(str3)); // 👉️ false
console.log(alphanumeric(str4)); // 👉️ true
console.log(alphanumeric(str5)); // 👉️ true

Upvotes: 3

Related Questions