Javascript regex for checking alphanumeric text with spaces and rejecting special characters

I am not a regular expression expert, but tried to check the correctness of the field, which allows alphanumeric data with spaces, but not any other special characters. Where linkTitle is the name of the variable to test, which I tried using the following regular expression in my conditional

/[^A-Za-z\d\s]/.test(linkTitle) /[^A-Za-z0-9\s]/.test(linkTitle) /[^A-Za-z\d ]/.test(linkTitle) 

and none of them worked ... I'm curious to see what went wrong with the regex using \ s, which seems to refer to spaces and that would be a suitable regex to match the count.

Thanks in advance!

+7
source share
2 answers

I think you want to combine the beginning of a line once, then use Positive Closing - one or more of your letters, spaces or numbers, and then the end of the line.

 /^[A-Za-z\d\s]+$/.test(linkTitle) 

Tested with

 var reg = /^[A-Za-z\d\s]+$/; ["Adam", "Ada m", "A1dam", "A!dam", 'sdasd 213123&*&*&'].forEach(function (str) { console.log(reg.test(str + "\n")); }); 

Shows true , true , true , false , false


Or if you want to allow blank lines, you can use the same RegEx, but with Clleure Kleene - zero or more letters, numbers or spaces

 var regAllowEmpty = /^[A-Za-z\d\s]*$/; ["", "Adam", "Ada m", "A1dam", "A!dam", 'sdasd 213123&*&*&'].forEach(function (str) { console.log(regAllowEmpty.test(str + "\n")); }); 

note that forEach will not work in older browsers - it's just for testing

+17
source

Any of your three regular expressions will match any single character that is not one between [ and ] except ^ , of course.

The problem may be related to how you interpret the result provided by test() . Here, if the regular expression matches the linkTitle string, and test returns true; this means that you received the wrong char on the input (neither a capital letter, nor a lowercase, not a number, not a space).

Check your regular expressions:

 /[^A-Za-z\d\s]/.test('0 '); // no match, false, input is ok /[^A-Za-z\d\s]/.test('0 $'); // match, true, input is wrong 
+1
source

All Articles