Categories
JavaScript Answers

How to check for alphanumeric, dash and underscore but no spaces with JavaScript?

Spread the love

Sometimes, we want to check for alphanumeric, dash and underscore but no spaces with JavaScript.

In this article, we’ll look at how to check for alphanumeric, dash and underscore but no spaces with JavaScript.

How to check for alphanumeric, dash and underscore but no spaces with JavaScript?

To check for alphanumeric, dash and underscore but no spaces with JavaScript, we can use a regex.

For instance, we write

const regExp = /^[a-zA-Z0-9-_]+$/;
const check = "foobar";
if (check.search(regExp) === -1) {
  alert("invalid");
} else {
  alert("valid");
}

to create the regExp regex that matches alphanumeric characters, dashes, and undescores through the string we’re checking.

We call check.search with the regExp to find the first match of the pattern.

If search returns -1, then there’re no matches.

Otherwise, the index of the first match in the string is returned.

Conclusion

To check for alphanumeric, dash and underscore but no spaces with JavaScript, we can use a regex.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *