javascript - 用 3 种模式替换字符串 "space", "and", "or"

标签 javascript regex string typescript

我正在使用 Angular 6 开发一个项目,我需要使用带正则表达式的替换方法用 3 种模式“空格”、“和”和“或”替换一个字符串。我可以用“and”和“or”来完成,但不能通过添加“space”来完成。用户将在搜索框中输入由 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+

错误 1:您使用\S 作为空格而不是\s。

\S Matches a character other than white space. Equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

错误 2:您在正则表达式的开头使用了\s

const value = new RegExp(searchValue.toLowerCase().replace(/ and | or |\s+/g, '|'));

let searchValue = "apple and pear or corn banana"
const value = new RegExp(searchValue.toLowerCase().replace(/ and | or |\s+/g, '|'));

console.log(value)

关于javascript - 用 3 种模式替换字符串 "space", "and", "or",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53414548/

相关文章:

javascript - 如何使用 CSS 溢出 : hidden to avoid the parent container grow

javascript - Bacon.js 的评估模型是什么?

regex - 我可以使用数据工厂数据流将列文本拆分为数组吗?

c - 如何遍历以空格分隔的每个单词?

c - 如何在第一个空格处拆分字符串并将字符串分配给不同的变量?

javascript - 将对象展平为数组?

Python多个正则表达式清理文件

java - 正则表达式用于搜索和替换字符串中的文本

javascript - 字符串过滤。需要去掉&lt;style&gt;标签及其内容,只保留<body>中的内容

javascript - 将 Vuex 与 Vuelidation 一起使用的正确方法