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!
Method #1 : Using all() + isspace() + isalpha() In this, we compare the string for all elements being alphabets or space only.
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 .
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.
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.
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:
i
flag in the end, which matches in a case-insensitive mannerIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With