5

Is it possible to work with Russian characters, in javascript's regex?
Maybe the use of \p{Cyrillic}?

If yes, please provide a basic example of usage.

The example:

var str1 = "абв прв фву";
var regexp = new RegExp("[вф]\\b", "g");

 alert(str1.replace(regexp, "X"));

I expect to get: абX прX

Cœur
  • 37,241
  • 25
  • 195
  • 267
samuel
  • 321
  • 2
  • 13

3 Answers3

7

Here is a good article on JavaScript regular expressions and unicode. Strings in JavaScript are 16 bit, so strings and RegExp objects can contain unicode characters, but most of the special characters like '\b', '\d', '\w' only support ascii. So your regular expression does not work as expected due to the use of '\b'. It seems you'll have to find a different way to detect word boundaries.

Annie
  • 6,621
  • 22
  • 27
6

It should work if you just save the JavaScript file in UTF8. Then you should be able to enter any character in a string.

edit: Just made a quick example with some cryllic characters from Wikipedia:

var cryllic = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяабвгдеёжзийклмнопрстуфхцчшщъыьэюя';
cryllic.match( 'л.+а' )[0];
// returns as expected: "лмнопрстуфхцчшщъыьэюяа"
poke
  • 369,085
  • 72
  • 557
  • 602
  • but if I try this: var str1 = "абв"; var regexp = new RegExp("[бв]\b", "g"); alert(str1.replace(regexp, "е")); it doesn't work. – samuel Dec 31 '09 at 17:18
  • Is your file 100% UTF-8 encoded? Can you try with a single character? – Pekka Dec 31 '09 at 18:01
  • 3
    It seems that the word boundary `\b` is not working correctly. If I remove it, it works correctly, so try replacing it by `[ ]` or something like that. – poke Dec 31 '09 at 18:08
  • I need to know the right " something like that". this is a simple example I need more complex regex patterns to work with, and need to use those tags. – samuel Dec 31 '09 at 18:46
1

According to this:

JavaScript, which does not offer any Unicode support through its RegExp class, does support \uFFFF for matching a single Unicode code point as part of its string syntax.

so you can at least use code points, but seemingly nothing more (no classes).

Also check out this duplicate of your question.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • That site is incorrect. JavaScript supports Unicode in regexps. – Eli Grey Dec 31 '09 at 17:54
  • I can't find any reference on more than comparing against single code points as I quoted above, see e.g. http://www.w3schools.com/jsref/jsref_obj_regexp.asp Do you have a source? – Pekka Dec 31 '09 at 18:03