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!
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!
Share Improve this question asked Sep 9, 2013 at 5:51 JoeJoe 8,27214 gold badges60 silver badges96 bronze badges 1- Oops I deleted the comment right before your response, I thought the answers were sufficient! – Nasser Al-Shawwa Commented Sep 9, 2013 at 5:59
2 Answers
Reset to default 13Your 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.
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:
- 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 - \d special character represents digits