Detect Russian / cyrillic in Javascript string?

Aerodynamika picture Aerodynamika · Nov 10, 2014 · Viewed 20.1k times · Source

I'm trying to detect if a string contains Russian (cyrillic) characters or not. I'm using this code:

term.match(/[\wа-я]+/ig);

but it doesn't work – or in fact it just returns the string back as it is.

Can somebody help with the right code?

Thanks!

Answer

Bohdan Lyzanets picture Bohdan Lyzanets · Nov 9, 2016

Use pattern /[\u0400-\u04FF]/ to cover more cyrillic characters:

// http://jrgraphix.net/r/Unicode/0400-04FF
const cyrillicPattern = /^[\u0400-\u04FF]+$/;

console.log('Привіт:', cyrillicPattern.test('Привіт'));
console.log('Hello:', cyrillicPattern.test('Hello'));

UPDATE:

In some new browsers, you can use Unicode property escapes.

The Cyrillic script uses the same range as described above: U+0400..U+04FF

const cyrillicPattern = /^\p{Script=Cyrillic}+$/u;

console.log('Привіт:', cyrillicPattern.test('Привіт'));
console.log('Hello:', cyrillicPattern.test('Hello'));