简体   繁体   English

如何防止 JavaScript 中正则表达式中的空格?

[英]How to prevent space in regex in JavaScript?

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.我在下面有这个 JavaScript 代码来删除给定单词中的空格(ستاک ئەڤەفلۆو),我在 Console.log 中尝试过,但它有一个问题。

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:以下是错误的output:

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

Which removes the space before the given string, so it merges the given string with the previous word.它删除了给定字符串之前的空格,因此它将给定字符串与前一个单词合并。

The output should be: output 应该是:

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

Thanks!谢谢!

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.我建议通过将单个 char 替代项合并到字符类中来删除转义,并通过仅删除第 2 组中的空格来解决此问题,而不是第 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 ' (^|[\s_«»[(<>']) - 捕获组 1(替换回调函数中的punct ):字符串开头,或空格, _ , « , » , [ , ( , < , >'
  • (ستاک ئەڤەفلۆو) - Capturing group 2 ( word ): some phrase (ستاک ئەڤەفلۆو) - 捕获组 2( word ):一些短语
  • (?=[«».،_\]\s:)<>؟'!]|$) - a positive lookahead that matches a location in string that is immediately followed by « , » , . (?=[«».،_\]\s:)<>؟'!]|$) - 匹配字符串中紧跟« , » , 的位置的正向前瞻. , ، , _ , ] , 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, '') ).匹配时,将punct (如果匹配)附加到从所有空格中删除的word (使用word.replace(/\s+/gi, '') )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM