【发布时间】:2019-04-24 04:03:23
【问题描述】:
我正在使用 Angular 6 开发一个项目,我需要使用带有正则表达式的替换方法将字符串替换为 3 种模式“空格”、“与”和“或”。我可以用“and”和“or”来做到这一点,但不能通过添加“空格”来做到这一点。用户将在搜索框中输入由 3 种模式中的任何一种分隔的单词。
这行得通:
const value = new RegExp(searchValue.toLowerCase().replace(/ and | or /g, '|'));
// Input: apple and pear or corn
// Output: /apple|pear|corn/
这不起作用:
const value = new RegExp(searchValue.toLowerCase().replace(/ \S+ | and | or /g, '|'));
我知道为了用空格替换你做.replace(/ /g, '|')),但我需要用“and”和“or”用同样的方法来替换空格。
如何做到这一点?先感谢您。
【问题讨论】:
-
您可以将其用作正则表达式 ` 和 |或 | \s*` 虽然这会选择所有后续空格
-
感谢您的回答。这有效: const value = new RegExp(searchVal.toLowerCase().replace(/ and | or |\s+/g, '|'));
-
我的荣幸。玩得开心。
标签: javascript regex string typescript