Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string has any non ISO-8859-1 characters with Javascript?

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);
like image 936
abhishekd Avatar asked Sep 29 '15 18:09

abhishekd


1 Answers

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.

like image 77
Buzinas Avatar answered Oct 30 '22 20:10

Buzinas