Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to check if string contains Alphanumeric Characters and Spaces only - javascript

This is what I have so far:

function checkTitle(){
    reg = /^[\w ]+$/;
    a = reg.test($("#title").val());    
    console.log(a);
}

So far in my tests it catches all special characters except _. How do I catch all special characters including _ in the current function?

I need the string to only have Alphanumeric Characters and Spaces. Appreciate the help cause I am having a hard time understanding regex patterns.

Thanks!

like image 412
Jo E. Avatar asked Sep 09 '13 05:09

Jo E.


People also ask

How do you check if a string contains only alphabets and space?

Method #1 : Using all() + isspace() + isalpha() In this, we compare the string for all elements being alphabets or space only.

How do you check if a string contains only alphabets and numbers in JavaScript?

To check if a string contains only letters and numbers in JavaScript, call the test() method on this regex: /^[A-Za-z0-9]*$/ . If the string contains only letters and numbers, this method returns true . Otherwise, it returns false .

How do you check if a string only has letters and numbers?

To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.


2 Answers

Your problem is that \w matches all alphanumeric values and underscore.

Rather than parsing the entire string, I'd just look for any unwanted characters. For example

var reg = /[^A-Za-z0-9 ]/;

If the result of reg.test is true, then the string fails validation.

like image 63
Phil Avatar answered Sep 22 '22 00:09

Phil


Since you are stating you are new to RegExp, I might as well include some tips with the answer. I suggest the following regexp:

/^[a-z\d ]+$/i

Here:

  1. There is no need for the upper case A-Z because of the i flag in the end, which matches in a case-insensitive manner
  2. \d special character represents digits
like image 21
nasser-sh Avatar answered Sep 20 '22 00:09

nasser-sh