Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To allow only alphanumeric and space, use this regex /^[a-z\d\s]+$/i it will return true if value contain only alphanumeric and spaces.

Let’s see short example to use regex in javascript

const regex = /^[a-z\d\s]+$/i;
console.log(regex.test("hello 8943"))

Today, I’m going to show you How do I check value contain only alphanumeric and space 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 alphanumeric and space in javascript using regex?

If you want to also allow underscore and hyphen use this regex /^[a-z\d\-_\s]+$/i.

Here, I will show allow only alphanumeric and space in javascript and typescript.

Javascript regex allow only alphanumeric and space example

Here, we will create common validate function where we will validate param should numbers and dots.

const regex = /^[a-z\d\s]+$/i;

// Truthy values
// word string
console.log(regex.test("INFINIT"))

// word with space
console.log(regex.test("INF INIT"))

// word with number
console.log(regex.test("INFINIT 374"))

// number with space
console.log(regex.test("3546 374"))

// Falsy values
// empty string
console.log(regex.test(""))

// hyphen
console.log(regex.test("INF-INIT"))

// plus
console.log(regex.test("INFINIT+374"))

// underscore
console.log(regex.test("3546_374"))

Output

Typescript regex allow only alphanumeric and space example

Same like javascript, we will create a function and call it with diffrent parameters.

const regex = /^[a-z\d\s]+$/i;

// Truthy values
// word string
console.log(regex.test("INFINIT"))

// word with space
console.log(regex.test("INF INIT"))

// word with number
console.log(regex.test("INFINIT 374"))

// number with space
console.log(regex.test("3546 374"))

// Falsy values
// empty string
console.log(regex.test(""))

// hyphen
console.log(regex.test("INF-INIT"))

// plus
console.log(regex.test("INFINIT+374"))

// underscore
console.log(regex.test("3546_374"))

Output

I hope it helps you, All the best đź‘Ť.