简体   繁体   中英

Regex pattern if string contains characters

Sorry for being an absolute beginner, when it comes to Javascript and Regex,

I have a Codepen: http://codepen.io/anon/pen/dNJNvK

What I want to accomplish is to validate, if a String contains some special UTF-8 characters. That's why I work with RegExp. The pattern I have here will return false only if the string to test equals one of the characters. But I want to return false if it contains one of these characters.

How can I accomplish this, I know it should be quite easy, but I wasn't able to get it working.

 var regEx = new RegExp('[\-\ÿ]'); console.log("This should be true: " + regEx.test("Tes")); console.log("This should be false: " + regEx.test("Tes ")); console.log("This returns false, because the string equals a special character: " + regEx.test(" ")); 

Why not the other way around?

See Regular expression to match non-English characters?

Also your test could be match instead or a test of the WHOLE string

 var regEx = /[\\x00-\\x7F]/g; // can be added to function okChar(str) { var res = str.match(regEx); if (res===null) return false; return res.length===str.length; } console.log("This should be true: " + okChar("Tes")) console.log("This should be false: " + okChar("Tesú")); console.log("This returns false, because the string equals a special character: " + okChar("ú")); 

as @Gabriel commented, it's returning true because there's at least one character in the string that matches your range

what you want to do is check that every character is within the range

/^[\u0001-\u00FF]+$/

or that any character is not within the range

[^\u0001-\u00FF]

in the second case you'd have true when a special character is used and false when all characters are safe, so you probably have to flip the checks you do afterward

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM