How to prevent space in regex in JavaScript?

Viewed 138

I have this JavaScript code below to remove spaces in the given words (ستاک ئەڤەفلۆو), and I tried it in Console.log, but it has a problem.

var text = "ئایا ستاک ئەڤەفلۆو مانای چییە؟ دووبارە ستاک ئەڤەفلۆو مانای چییە؟";

text = text.replace(
            new RegExp("(^|\\s|_|«|»|\\[|\\(|\\<|\\>|\\')(ستاک ئەڤەفلۆو)(?= |«|»|\\.|،|_|\\]|\\s|\\:|\\)|\\<|\\>|؟|\\'|\\!|$)", 'g'),
            function (x) { return x.replace(/ /gi, ''); } // 'i' is just to trick bidi algorithm on code view
        );

The following is the wrong output:

ئایاستاکئەڤەفلۆو مانای چییە؟ دووبارەستاکئەڤەفلۆو مانای چییە؟

Which removes the space before the given string, so it merges the given string with the previous word.

The output should be:

ئایا ستاکئەڤەفلۆو مانای چییە؟ دووبارە ستاکئەڤەفلۆو مانای چییە؟

Thanks!

1 Answers

I suggest removing escapes by merging single char alternatives into character classes, and fix the issue by removing whitespaces in Group 2 only, not in Group 1.

var text = "ئایا ستاک ئەڤەفلۆو مانای چییە؟ دووبارە ستاک ئەڤەفلۆو مانای چییە؟";

text = text.replace(
  new RegExp("(^|[\\s_«»[(<>'])(ستاک ئەڤەفلۆو)(?=[«».،_\\]\\s:)<>؟'!]|$)", 'g'),
  function (x, punct, word) { return (punct || "") + word.replace(/\s+/gi, ''); }
);
console.log(text)

So, the regex means

  • (^|[\s_«»[(<>']) - Capturing group 1 (punct in the replacement callback function): start of string, or a whitespace, _, «, », [, (, <, > or '
  • (ستاک ئەڤەفلۆو) - Capturing group 2 (word): some phrase
  • (?=[«».،_\]\s:)<>؟'!]|$) - a positive lookahead that matches a location in string that is immediately followed by «, », ., ،, _, ], whitespace, :, ), <, >, ؟, ', ! or end of string.

Upon a match, punct (if matched) is appended to the word that is stripped from all whitespaces (with word.replace(/\s+/gi, '')).

Related