I want to write a string validator (or regex) for ISO-8859-1 characters in Javascript.
If a string has any non ISO-8859-1 character, then validator must return false
otherwise true
. E.g:
str = "abcÂÃ";
validator(str); // should return true;
str = "a 你 好";
validator(str); // should return false;
str ="你 好";
validator(str); // should return false;
I have tried to use the following regex but it's not working perfectly.
var regex = /^[\u0000-\u00ff]+/g;
var res = regex.test(value);
Since you want to return false if any non-ISO-8859-1 character is present, you could use double-negate:
var str = "abcÂÃ";
console.log(validator(str)); // should return true;
str = "a 你 好";
console.log(validator(str)); // should return false;
str = "你 好";
console.log(validator(str)); // should return false;
str = "abc";
console.log(validator(str)); // should return true;
str = "╗";
console.log(validator(str)); // should return false;
function validator(str) {
return !/[^\u0000-\u00ff]/g.test(str);
}
It uses !/[^\u0000-\u00ff]/g.test(str)
, since it checks if there is any non-character, and if it has not, it returns true
, otherwise, it returns false
.
If 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