【问题标题】:Join Regex Expression Array加入正则表达式数组
【发布时间】:2015-03-24 09:24:40
【问题描述】:

我有一个单词数组,例如苹果,香蕉,马,我想在以后的函数中作为分割点。

我发现了如何连接正则表达式,但它适用于固定数量的表达式: How can I concatenate regex literals in JavaScript?

问题: 如何加入正则表达式数组?

filterTemp = [];
for (i = 0, len = filterWords.length; i < len; i++) {
  word = filterWords[i];
  filterTemp.push(new RegExp("\b" + word + "\b"));
}
filter = new RegExp(filterTemp.source.join("|"), "gi");
return console.log("filter", filter);

【问题讨论】:

  • filterTemp.push(new RegExp("\\b" + word + "\\b"));

标签: javascript regex


【解决方案1】:

您不需要在循环内构造RegExp,只需将字符串推入临时数组,然后在外部仅使用一次join即可构造RegExp对象:

var filterWords = ['abc', 'foo', 'bar'];
var filterTemp = [];
for (i = 0, len = filterWords.length; i < len; i++) {
  filterTemp.push("\\b" + filterWords[i] + "\\b");
}

filter = new RegExp(filterTemp.join("|"), "gi");
console.log("filter", filter);
//=> /\babc\b|\bfoo\b|\bbar\b/gi

【讨论】:

  • 请注意filter = new RegExp(filterTemp.source.join("|"), "gi"); 应该是filter = new RegExp(filterTemp.join("|"), "gi");
【解决方案2】:

2022 年:

const validate = (val: string) => {
  const errorMessage =
    'Enter the time separated by commas. For example: 12:30, 22:00, ... etc.';
  const values = val.split(',').map((val: string) => val.trim());
  const filter = new RegExp(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/);
  const isValid = values.some(
    (value: string) => !filter.test(value),
  );
  return !isValid || errorMessage;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多