我正在使用 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/