让我们考虑以下字符串text
“我刚刚在汉堡土地上尝试了新汉堡!” 以及以下字符串数组 ["eat", "burger", "fries"]
我想要的是知道text
数组中是否存在任何单词,但是以优化的方式......不仅仅是两个for循环......
有任何想法吗?
您可以通过加入数组以创建字符串来通过正则表达式执行此操作。
正则表达式参考
通过 JavaScript 创建 RegEx 字符串后,它看起来像这样(字符串转义已删除):
\b(?:eat|burger|fries)\b
const str = 'I just tried the new burgers in burger land!'
const arr = ['eat', 'burger', 'fries']
// "\b" This is a word boundary - Allows you to perform a "whole words only" search
// "(?:xxx)" This is a non-capturing group. It's not stored in memory to be referenced later on.
// 'arr.join()' creates the following string: "eat|burger|fries"
console.log(str.match(new RegExp(`\\b(?:${arr.join('|')})\\b`, 'ig')))
如果需要转义正则表达式是一个问题,您可以通过转义特殊字符来实现。并映射需要测试的单词数组。
const str = 'I just tried the new burgers in burger land!'
const arr = ['eat', 'burger', 'fries', '(']
const esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
console.log(str.match(new RegExp(`\\b(?:${arr.map(esc).join('|')})\\b`, 'ig')))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句