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

JavaScript

梅路易

2020-03-09

我想String.replaceAll()在JavaScript中创建一个方法,并且我认为使用正则表达式是最简洁的方法。但是,我不知道如何将变量传递给正则表达式。我能做到这一点已经将取代所有的实例"B""A"

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

但是我想做这样的事情:

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

但是显然这只会替换文本"replaceThis"...所以如何将这个变量传递给我的正则表达式字符串?

第279篇《如何在正则表达式中使用变量?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

10个回答
神无Sam乐 2020.03.09

For multiple replace without regular expressions I went with the following:

      let str = "I am a cat man. I like cats";
      let find = "cat";
      let replace = "dog";


      // Count how many occurrences there are of the string to find 
      // inside the str to be examined.
      let findCount = str.split(find).length - 1;

      let loopCount = 0;

      while (loopCount < findCount) 
      {
        str = str.replace(find, replace);
        loopCount = loopCount + 1;
      }  

      console.log(str);
      // I am a dog man. I like dogs

The important part of the solution was found here

梅乐 2020.03.09

Your solution is here:

Pass a variable 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 another is the "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.

JavaScript code:

  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 fields with which I want to replace another 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.

So now You can pass variable in replace function.

GOL蛋蛋 2020.03.09

None of these answers were clear to me. I eventually found a good explanation at http://burnignorance.com/php-programming-tips/how-to-use-a-variable-in-replace-function-of-javascript/

The simple answer is:

var search_term = new RegExp(search_term, "g");    
text = text.replace(search_term, replace_term);

For example:

$("button").click(function() {
  Find_and_replace("Lorem", "Chocolate");
  Find_and_replace("ipsum", "ice-cream");
});

function Find_and_replace(search_term, replace_term) {
  text = $("textbox").html();
  var search_term = new RegExp(search_term, "g");
  text = text.replace(search_term, replace_term);
  $("textbox").html(text);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textbox>
  Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
</textbox>
<button>Click me</button>

LEY番长 2020.03.09

You can use this if $1 not work with you

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

You can always use indexOf repeatedly:

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.

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

用这个工具测试

布雷西 2020.03.09

您想动态地构建正则表达式,为此,正确的解决方案是使用new RegExp(string)构造函数。为了使构造函数按字面意义处理特殊字符,必须对它们进行转义。jQuery UI自动完成小部件中有一个内置函数,称为$.ui.autocomplete.escapeRegex

您可以利用内置 $.ui.autocomplete.escapeRegex功能。它只需要一个字符串参数,并转义所有正则表达式字符,从而可以安全地将结果传递给new RegExp()

如果您使用的是jQuery UI,则可以使用该函数,也可以从源代码复制其定义

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

并像这样使用它:

"[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]"
Stafan猴子 2020.03.09

这个:

var txt=new RegExp(pattern,attributes);

等效于此:

var txt=/pattern/attributes;

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

Vicky 2020.03.09

正如Eric Wendelin所述,您可以执行以下操作:

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

这产生了"regex matching ."但是,如果str1为,它将失败"."您希望结果是"pattern matching regex",用代替句点"regex",但结果是...

regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex

这是因为,尽管它"."是一个字符串,但在RegExp构造函数中,它仍被解释为正则表达式,表示任何非换行符,表示字符串中的每个字符。为此,以下功能可能有用:

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

然后,您可以执行以下操作:

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

屈服"pattern matching regex"

米亚十三Harry 2020.03.09

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

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

您可以通过这种方式动态创建正则表达式对象。然后,您将执行以下操作:

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android