Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace exact match in cyrillic

I want to use regex for string replace with Cyrillic characters. I want to use exact match option. My string replace is working with Latin characters and is looking like that:

'Edin'.replace(/\Edin\b/gi, '');  // Output is ""

The same expression is not working with Cyrillic characters

'Един'.replace(/\Един\b/gi, '');  // Output is still 'Един'
like image 864
user732456 Avatar asked Sep 26 '14 07:09

user732456


2 Answers

The problem here is \b word boundary chracter, which matches position at a word boundary. Word boundary is defined as (^\w|\w$|\W\w|\w\W). And in its turn word character \w is a set of ASCII characters [A-Za-z0-9_]. Obviously Cyrillic characters don't fall into this set.

For example, for the same reason /\w+/ regular expression will not match Cyrillyc string.

like image 197
dfsq Avatar answered Sep 29 '22 02:09

dfsq


As dfsq wrote the problem is with word boundary. If you remove \b you will get desired output, but it is quite different regex. It will replace Един also in cases where it is a part of word. To avoid that you can use negative lookahead and define which letters shouldn't appear behind, because they could be a part of word.

'Един'.replace(/\Един(?![A-я])/gi, ''); 
like image 33
Iale Avatar answered Sep 29 '22 01:09

Iale