i would like to check string using js's regex. i would like write a pattern which is like this; if string contains [^a-zA-Z0-9_] return must be true else return must be false.
开发者_Python百科Thank you very for your help already now.
Use .test
:
/[^a-zA-Z0-9_]/.test(str);
Edit:
/[^a-zA-Z0-9_İıĞğÇçÖöÜüÖö]/.test(str);
However, your regular expression will basically check whether there is a character that's not in that list in your string. I don't see the practical use of that. Is it indeed what you're trying to acoomplish?
e.g. a
will fail, a-
will not fail because the -
does match the regexp.
Edit 2: If you want to make sure the string contains only certain characters, use this:
/^[a-zA-Z0-9_-İıĞğÇçÖöÜüÖö]*$/.test(str);
What it does is checking whether there are one or more of the characters of that list in the string, and ^...$
means that it only matches the complete string, so that a%
or something like that does not pass (otherwise it would match the a
and return true
).
Edit 3: If a string should not contain any of a list of characters, use e.g.:
/^[^İıĞğÇçÖöÜüÖö]*$/.test(str); // returns true if there are not any of those characters in the string
var string = 'Hello Sir';
var isMatch = /[^a-zA-Z0-9_]/.test(string);
return /\w/.test(string); // matches Letters,Numbers,and underscore.
精彩评论