Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't replace space with Zero-width space using RegExp

i have this string "می آییم و می رویم". and i want to replace space after "mi" (می) with Zero-width space.

here is the regex which work's fine in PHP:

preg_replace("#((\s\x{0645}\x{06CC})+( )+([\x{0600}-\x{06EF}]{1,}){1,})#u", "$2\xE2\x80\x8C$4", $value, 1);

and here is the regex for javascript which does not work:

  pattern = /((\s\\x{0645}\\x{06CC})+( )+([\\x{0600}\-\\x{06EF}]{1,}){1,})/g;
  value = value.replace( new RegExp(pattern), "$2\xE2\x80\x8C$4" );

1 Answers

In JavaScript you need to use \u0abc instead of \x{0abc} for Unicode characters. I also refactored the use of the PHP look back parameters ($2 and $4) as they do not exist as such in JavaScript.

var str = `می آییم و می رویم`
var regex = new RegExp(/(\s\u0645\u06CC)+( )+([\u0600-\u06EF]{1,}){1,}/g)

matches = regex.exec(str);
document.write(str.replace(matches[1]+' '+matches[3],matches[1]+'\u200C'+matches[3]))
like image 59
Alex Avatar answered Apr 30 '26 16:04

Alex