在Javascript中添加多个变量以使用RegEx函数

Add more than one variable in Javascript to work with the RegEx function

本文关键字:RegEx 函数 变量 Javascript 添加      更新时间:2023-09-26

这篇文章详细介绍了如何在正则表达式中包含变量,但它只展示了如何包含一个变量。我目前正在使用正则表达式的match函数来查找前导字符串和尾随字符串之间的字符串。我的代码如下:

array = text.match(/SomeLeadingString(.*?)SomeTrailingString/g);

现在,我如何构建一个具有与此相同功能的正则表达式,但不是在表达式中实际使用两个字符串,而是希望能够在外部创建它们,如下所示:

var startString = "SomeLeadingString"
var endString = "SomeTrailingString"

所以,我的最后一个问题是,如何将startString和endString包含在上面列出的正则表达式中,以便功能相同?谢谢

使用RegExp对象将字符串连接到regex

const reg = new RegExp(`${startString}(''w+)${endString}`,"g");
const matches = text.match(reg);

注意

连接字符串时,建议转义none regex字符串:(转义模式取自此答案)

const escapeReg = (str)=>str.replace(/[-'/''^$*+?.()|[']{}]/g, '''$&');

示例

我们有字符串(.*)hello??,我们想在(.*)?? 之间匹配单词

我们会做一些类似的事情:

const prefix = "(.*)";
const suffix = "??";
const reg = new RegExp(`${escapeReg(prefix)}(''w+)${escapeReg(suffix)}`);
const result = "(.*)hello??".match(reg);
if(result){
   console.log(result[1]); //"hello"
}