如何在正则表达式中使用变量?

时间:2021-03-01 23:08:31

I would like to create a String.replaceAll() method in JavaScript and I'm thinking that using a RegEx would be most terse way to do it. However, I can't figure out how to pass a variable in to a RegEx. I can do this already which will replace all the instances of "B" with "A".

我想在JavaScript中创建String.replaceAll()方法,我认为使用RegEx是最简洁的方法。但是,我不知道如何将变量传递给RegEx。我已经可以用A来代替B的所有实例了。

"ABABAB".replace(/B/g, "A");

But I want to do something like this:

但我想这样做:

String.prototype.replaceAll = function(replaceThis, withThis) {
    this.replace(/replaceThis/g, withThis);
};

But obviously this will only replace the text "replaceThis"...so how do I pass this variable in to my RegEx string?

但显然,这只会替换文本“replaceThis”……那么如何将这个变量传递给RegEx字符串呢?

17 个解决方案

#1


1351  

Instead of using the /regex/g syntax, you can construct a new RegExp object:

不使用/regex/g语法,您可以构造一个新的RegExp对象:

var replace = "regex";
var re = new RegExp(replace,"g");

You can dynamically create regex objects this way. Then you will do:

您可以以这种方式动态创建regex对象。然后你会做什么:

"mystring".replace(re, "newstring");

#2


167  

As Eric Wendelin mentioned, you can do something like this:

正如Eric Wendelin所说,你可以做这样的事情:

str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");

This yields "regex matching .". However, it will fail if str1 is ".". You'd expect the result to be "pattern matching regex", replacing the period with "regex", but it'll turn out to be...

这会产生“regex匹配”。然而,如果str1是“,它就会失败”。您可能希望结果是“模式匹配regex”,用“regex”替换这段时间,但结果是……

regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex

This is because, although "." is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful:

这是因为,虽然“.”是一个字符串,但在RegExp构造函数中,它仍然被解释为一个正则表达式,表示任何非换行字符,表示字符串中的每个字符。为此目的,下列职能可能有用:

 RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
 };

Then you can do:

然后你可以做:

str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");

yielding "pattern matching regex".

产生“模式匹配正则表达式”。

#3


81  

"ABABAB".replace(/B/g, "A");

“ABABAB”。替换(/ B / g,“A”);

As always: don't use regex unless you have to. For a simple string replace, the idiom is:

一如既往:除非必要,否则不要使用regex。对于简单的字符串替换,习惯用法是:

'ABABAB'.split('B').join('A')

Then you don't have to worry about the quoting issues mentioned in Gracenotes's answer.

这样你就不用担心Gracenotes所提到的引用问题了。

#4


26  

For anyone looking to use variable with the match method, this worked for me

对于任何想用match方法来使用变量的人来说,这对我很有用。

var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight

#5


20  

This:

这样的:

var txt=new RegExp(pattern,attributes);

is equivalent to this:

等价于:

var txt=/pattern/attributes;

See http://www.w3schools.com/jsref/jsref_obj_regexp.asp.

见http://www.w3schools.com/jsref/jsref_obj_regexp.asp。

#6


13  

this.replace( new RegExp( replaceThis, 'g' ), withThis );

#7


9  

String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(replaceThis,"g"); 
   return this.replace(re, withThis);
};
var aa = "abab54..aba".replaceAll("\\.", "v");

Test with this tool

测试这个工具

#8


7  

You want to build the regular expression dynamically and for this the proper solutuion is to use the new RegExp(string) constructor. In order for constructor to treat special characters literally, you must escape them. There is a built-in function in jQuery UI autocomplete widget called $.ui.autocomplete.escapeRegex:

您希望动态构建正则表达式,为此,正确的解决方案是使用新的RegExp(string)构造函数。为了构造函数从字面上处理特殊字符,您必须转义它们。jQuery UI自动完成小部件中有一个内置函数,名为$.ui.autocomplete.escapeRegex:

[...] you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().

[…你可以使用内置的$. ui.autocomplete.escaperegex函数。它将使用一个字符串参数并转义所有regex字符,使结果安全地传递到新的RegExp()。

If you are using jQuery UI you can use that function, or copy its definition from the source:

如果您正在使用jQuery UI,您可以使用该函数,或者从源代码中复制它的定义:

function escapeRegex(value) {
    return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}

And use it like this:

像这样使用它:

"[z-a][z-a][z-a]".replace(new RegExp(escapeRegex("[z-a]"), "g"), "[a-z]");
//            escapeRegex("[z-a]")       -> "\[z\-a\]"
// new RegExp(escapeRegex("[z-a]"), "g") -> /\[z\-a\]/g
// end result                            -> "[a-z][a-z][a-z]"

#9


3  

While you can make dynamically-created RegExp's (as per the other responses to this question), I'll echo my comment from a similar post: The functional form of String.replace() is extremely useful and in many cases reduces the need for dynamically-created RegExp objects. (which are kind of a pain 'cause you have to express the input to the RegExp constructor as a string rather than use the slashes /[A-Z]+/ regexp literal format)

虽然您可以创建动态创建的RegExp(与对这个问题的其他响应一样),但是我将从类似的文章中重复我的评论:String.replace()的函数形式非常有用,并且在许多情况下减少了对动态创建RegExp对象的需要。(这有点麻烦,因为您必须将RegExp构造函数的输入表示为字符串,而不是使用斜线/[a - z]+/ RegExp文本格式)

#10


3  

Here's another replaceAll implementation:

这是另一个replaceAll实现:

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if ( stringToFind == stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

#11


3  

To satisfy my need to insert a variable/alias/function into a Regular Expression, this is what I came up with:

为了满足我在正则表达式中插入变量/别名/函数的需要,这就是我所想到的:

oldre = /xx\(""\)/;
function newre(e){
    return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};

String.prototype.replaceAll = this.replace(newre(oldre), "withThis");

where 'oldre' is the original regexp that I want to insert a variable, 'xx' is the placeholder for that variable/alias/function, and 'yy' is the actual variable name, alias, or function.

其中'oldre'是我要插入变量的原始regexp, 'xx'是该变量/别名/函数的占位符,'yy'是实际的变量名、别名或函数。

#12


3  

String.prototype.replaceAll = function(a, b) {
    return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
}

Test it like:

测试:

var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'

console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))

#13


3  

And the coffeescript version of Steven Penny's answer, since this is #2 google result....even if coffee is just javascript with a lot of characters removed...;)

和史蒂文一分钱的coffeescript版本的答案,因为这是# 2谷歌结果....即使咖啡只是去掉了很多字符的javascript……

baz = "foo"
filter = new RegExp(baz + "d")
"food fight".match(filter)[0] // food

and in my particular case

在我的例子中

robot.name=hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
  console.log "True!"

#14


1  

You can use this if $1 not work with you

如果$1不与您一起使用,您可以使用它。

var pattern = new RegExp("amman","i");
"abc Amman efg".replace(pattern,"<b>"+"abc Amman efg".match(pattern)[0]+"</b>");

#15


1  

You can always use indexOf repeatedly:

你可以反复使用indexOf:

String.prototype.replaceAll = function(substring, replacement) {
    var result = '';
    var lastIndex = 0;

    while(true) {
        var index = this.indexOf(substring, lastIndex);
        if(index === -1) break;
        result += this.substring(lastIndex, index) + replacement;
        lastIndex = index + substring.length;
    }

    return result + this.substring(lastIndex);
};

This doesn’t go into an infinite loop when the replacement contains the match.

当替换包含匹配时,它不会进入无限循环。

#16


1  

All your solution is here,

所有的解都在这里,

Pass a variabe to regular expression.

将一个变量传递给正则表达式。

The one which I have implemented is by taking the value from a text field which is the one you want to replace and and another is "replace with" text field,

我实现的方法是从一个文本字段中取值这是你想要替换的另一个是"替换为"文本字段,

getting the value from text-field in a variable and setting the variable to RegExp function to further replace.In my case I am using Jquery,You also can do it by only javaScript too.

从变量中获取文本字段的值,并将变量设置为RegExp函数以进一步替换。在我的例子中,我使用的是Jquery,您也只能使用javaScript。

JavaScript code:

JavaScript代码:

  var replace =document.getElementById("replace}"); // getting a value from a text field with I want to replace
  var replace_with = document.getElementById("with");        //Getting the value from another text fiels with which I want to replace anather string.

  var sRegExInput = new RegExp(replace, "g");    
  $("body").children().each(function() {
    $(this).html($(this).html().replace(sRegExInput,replace_with));
  });

This code is on Onclick event of a button,You can put this in a function to call.

这个代码是在Onclick事件的一个按钮,你可以把这个放在一个函数中调用。

So now You can pass variable in replace function.

现在你可以在replace函数中传递变量。

#17


1  

If you want to get ALL occurrences (g), be case insensitive (i), and use boundaries so that it isn't a word within another word (\\b):

如果你想要得到所有的事件(g),不区分大小写(i),并使用边界,使它不是另一个单词(\ b)中的一个单词:

re = new RegExp(`\\b${replaceThis}\\b`, 'gi');

Example:

例子:

let inputString = "I'm John, or johnny, but I prefer john.";
let replaceThis = "John";
let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.

#1


1351  

Instead of using the /regex/g syntax, you can construct a new RegExp object:

不使用/regex/g语法,您可以构造一个新的RegExp对象:

var replace = "regex";
var re = new RegExp(replace,"g");

You can dynamically create regex objects this way. Then you will do:

您可以以这种方式动态创建regex对象。然后你会做什么:

"mystring".replace(re, "newstring");

#2


167  

As Eric Wendelin mentioned, you can do something like this:

正如Eric Wendelin所说,你可以做这样的事情:

str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");

This yields "regex matching .". However, it will fail if str1 is ".". You'd expect the result to be "pattern matching regex", replacing the period with "regex", but it'll turn out to be...

这会产生“regex匹配”。然而,如果str1是“,它就会失败”。您可能希望结果是“模式匹配regex”,用“regex”替换这段时间,但结果是……

regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex

This is because, although "." is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful:

这是因为,虽然“.”是一个字符串,但在RegExp构造函数中,它仍然被解释为一个正则表达式,表示任何非换行字符,表示字符串中的每个字符。为此目的,下列职能可能有用:

 RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
 };

Then you can do:

然后你可以做:

str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");

yielding "pattern matching regex".

产生“模式匹配正则表达式”。

#3


81  

"ABABAB".replace(/B/g, "A");

“ABABAB”。替换(/ B / g,“A”);

As always: don't use regex unless you have to. For a simple string replace, the idiom is:

一如既往:除非必要,否则不要使用regex。对于简单的字符串替换,习惯用法是:

'ABABAB'.split('B').join('A')

Then you don't have to worry about the quoting issues mentioned in Gracenotes's answer.

这样你就不用担心Gracenotes所提到的引用问题了。

#4


26  

For anyone looking to use variable with the match method, this worked for me

对于任何想用match方法来使用变量的人来说,这对我很有用。

var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight

#5


20  

This:

这样的:

var txt=new RegExp(pattern,attributes);

is equivalent to this:

等价于:

var txt=/pattern/attributes;

See http://www.w3schools.com/jsref/jsref_obj_regexp.asp.

见http://www.w3schools.com/jsref/jsref_obj_regexp.asp。

#6


13  

this.replace( new RegExp( replaceThis, 'g' ), withThis );

#7


9  

String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(replaceThis,"g"); 
   return this.replace(re, withThis);
};
var aa = "abab54..aba".replaceAll("\\.", "v");

Test with this tool

测试这个工具

#8


7  

You want to build the regular expression dynamically and for this the proper solutuion is to use the new RegExp(string) constructor. In order for constructor to treat special characters literally, you must escape them. There is a built-in function in jQuery UI autocomplete widget called $.ui.autocomplete.escapeRegex:

您希望动态构建正则表达式,为此,正确的解决方案是使用新的RegExp(string)构造函数。为了构造函数从字面上处理特殊字符,您必须转义它们。jQuery UI自动完成小部件中有一个内置函数,名为$.ui.autocomplete.escapeRegex:

[...] you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().

[…你可以使用内置的$. ui.autocomplete.escaperegex函数。它将使用一个字符串参数并转义所有regex字符,使结果安全地传递到新的RegExp()。

If you are using jQuery UI you can use that function, or copy its definition from the source:

如果您正在使用jQuery UI,您可以使用该函数,或者从源代码中复制它的定义:

function escapeRegex(value) {
    return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}

And use it like this:

像这样使用它:

"[z-a][z-a][z-a]".replace(new RegExp(escapeRegex("[z-a]"), "g"), "[a-z]");
//            escapeRegex("[z-a]")       -> "\[z\-a\]"
// new RegExp(escapeRegex("[z-a]"), "g") -> /\[z\-a\]/g
// end result                            -> "[a-z][a-z][a-z]"

#9


3  

While you can make dynamically-created RegExp's (as per the other responses to this question), I'll echo my comment from a similar post: The functional form of String.replace() is extremely useful and in many cases reduces the need for dynamically-created RegExp objects. (which are kind of a pain 'cause you have to express the input to the RegExp constructor as a string rather than use the slashes /[A-Z]+/ regexp literal format)

虽然您可以创建动态创建的RegExp(与对这个问题的其他响应一样),但是我将从类似的文章中重复我的评论:String.replace()的函数形式非常有用,并且在许多情况下减少了对动态创建RegExp对象的需要。(这有点麻烦,因为您必须将RegExp构造函数的输入表示为字符串,而不是使用斜线/[a - z]+/ RegExp文本格式)

#10


3  

Here's another replaceAll implementation:

这是另一个replaceAll实现:

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if ( stringToFind == stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

#11


3  

To satisfy my need to insert a variable/alias/function into a Regular Expression, this is what I came up with:

为了满足我在正则表达式中插入变量/别名/函数的需要,这就是我所想到的:

oldre = /xx\(""\)/;
function newre(e){
    return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};

String.prototype.replaceAll = this.replace(newre(oldre), "withThis");

where 'oldre' is the original regexp that I want to insert a variable, 'xx' is the placeholder for that variable/alias/function, and 'yy' is the actual variable name, alias, or function.

其中'oldre'是我要插入变量的原始regexp, 'xx'是该变量/别名/函数的占位符,'yy'是实际的变量名、别名或函数。

#12


3  

String.prototype.replaceAll = function(a, b) {
    return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
}

Test it like:

测试:

var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'

console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))

#13


3  

And the coffeescript version of Steven Penny's answer, since this is #2 google result....even if coffee is just javascript with a lot of characters removed...;)

和史蒂文一分钱的coffeescript版本的答案,因为这是# 2谷歌结果....即使咖啡只是去掉了很多字符的javascript……

baz = "foo"
filter = new RegExp(baz + "d")
"food fight".match(filter)[0] // food

and in my particular case

在我的例子中

robot.name=hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
  console.log "True!"

#14


1  

You can use this if $1 not work with you

如果$1不与您一起使用,您可以使用它。

var pattern = new RegExp("amman","i");
"abc Amman efg".replace(pattern,"<b>"+"abc Amman efg".match(pattern)[0]+"</b>");

#15


1  

You can always use indexOf repeatedly:

你可以反复使用indexOf:

String.prototype.replaceAll = function(substring, replacement) {
    var result = '';
    var lastIndex = 0;

    while(true) {
        var index = this.indexOf(substring, lastIndex);
        if(index === -1) break;
        result += this.substring(lastIndex, index) + replacement;
        lastIndex = index + substring.length;
    }

    return result + this.substring(lastIndex);
};

This doesn’t go into an infinite loop when the replacement contains the match.

当替换包含匹配时,它不会进入无限循环。

#16


1  

All your solution is here,

所有的解都在这里,

Pass a variabe to regular expression.

将一个变量传递给正则表达式。

The one which I have implemented is by taking the value from a text field which is the one you want to replace and and another is "replace with" text field,

我实现的方法是从一个文本字段中取值这是你想要替换的另一个是"替换为"文本字段,

getting the value from text-field in a variable and setting the variable to RegExp function to further replace.In my case I am using Jquery,You also can do it by only javaScript too.

从变量中获取文本字段的值,并将变量设置为RegExp函数以进一步替换。在我的例子中,我使用的是Jquery,您也只能使用javaScript。

JavaScript code:

JavaScript代码:

  var replace =document.getElementById("replace}"); // getting a value from a text field with I want to replace
  var replace_with = document.getElementById("with");        //Getting the value from another text fiels with which I want to replace anather string.

  var sRegExInput = new RegExp(replace, "g");    
  $("body").children().each(function() {
    $(this).html($(this).html().replace(sRegExInput,replace_with));
  });

This code is on Onclick event of a button,You can put this in a function to call.

这个代码是在Onclick事件的一个按钮,你可以把这个放在一个函数中调用。

So now You can pass variable in replace function.

现在你可以在replace函数中传递变量。

#17


1  

If you want to get ALL occurrences (g), be case insensitive (i), and use boundaries so that it isn't a word within another word (\\b):

如果你想要得到所有的事件(g),不区分大小写(i),并使用边界,使它不是另一个单词(\ b)中的一个单词:

re = new RegExp(`\\b${replaceThis}\\b`, 'gi');

Example:

例子:

let inputString = "I'm John, or johnny, but I prefer john.";
let replaceThis = "John";
let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.