首页 文章

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

提问于
浏览
1043

我想在JavaScript中创建一个String.replaceAll()方法,我认为使用RegEx将是最简洁的方法 . 但是,我无法弄清楚如何将变量传递给RegEx . 我已经可以做到这一点,它将用“A”替换所有“B”的实例 .

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

但我想做这样的事情:

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

但显然这只会替换文本“replaceThis”...所以如何将此变量传递给我的RegEx字符串?

18 回答

  • 3

    您可以反复使用 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);
    };
    

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

  • 29

    “ABABAB”.replace(/ B / g,“A”);

    一如既往:除非必须,否则不要使用正则表达式 . 对于简单的字符串替换,成语是:

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

    那么你不必担心Gracenotes答案中提到的引用问题 .

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

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

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

    您可以通过这种方式动态创建正则表达式对象 . 然后你会做:

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

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

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

    这会产生 "regex matching ." . 但是,如果str1是 "." ,它将失败 . 你期望结果为 "pattern matching regex" ,用 "regex" 替换句号,但结果却是......

    regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex
    

    这是因为,尽管 "." 是一个String,但在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" .

  • 15

    如果要获取所有出现次数( g ),请区分大小写( i ),并使用边界使其不是另一个单词中的单词( \\b ):

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

    例:

    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.
    
  • 0

    如果1美元不能与你合作,你可以使用它

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

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

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

    这个:

    var txt=new RegExp(pattern,attributes);
    

    相当于:

    var txt=/pattern/attributes;
    

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

  • 3

    这是另一个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;
        };
    
  • 1468

    和Steven Penny的答案的coffeescript版本,因为这是#2 google结果....即使咖啡只是javascript,删除了很多字符...;)

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

    在我的特殊情况下

    robot.name=hubot
    filter = new RegExp(robot.name)
    if msg.match.input.match(filter)
      console.log "True!"
    
  • 1
    String.prototype.replaceAll = function(a, b) {
        return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
    }
    

    测试它像:

    var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'
    
    console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))
    
  • 6
    String.prototype.replaceAll = function (replaceThis, withThis) {
       var re = new RegExp(replaceThis,"g"); 
       return this.replace(re, withThis);
    };
    var aa = "abab54..aba".replaceAll("\\.", "v");
    

    用这个测试tool

  • 92

    您的解决方案在这里:

    Pass a variable to regular expression.

    我实现的是通过从要替换的文本字段中获取值,另一个是“替换为”文本字段,从变量中的text-field获取值并将变量设置为RegExp功能进一步取代 . 在我的情况下,我使用Jquery,你也可以只使用JavaScript .

    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 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));
      });
    

    这个代码是Onclick事件的一个按钮,你可以将它放在一个函数中来调用 .

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

  • 9

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

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

    'oldre'是我想插入变量的原始正则表达式,'xx'是该变量/别名/函数的占位符,'yy'是实际的变量名,别名或函数 .

  • 1

    这些答案都不清楚 . 我最终在http://burnignorance.com/php-programming-tips/how-to-use-a-variable-in-replace-function-of-javascript/找到了一个很好的解释

    简单的答案是:

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

    例如:

    $("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>
    
  • 25

    您想要动态构建正则表达式,为此,正确的解决方案是使用 new RegExp(string) 构造函数 . 为了让构造函数按字面意思处理特殊字符,您必须将它们转义 . jQuery UI autocomplete widget中有一个名为 $.ui.autocomplete.escapeRegex 的内置函数:

    [...]您可以使用内置的$ .ui.autocomplete.escapeRegex函数 . 它将采用单个字符串参数并转义所有正则表达式字符,从而使结果安全地传递给新的RegExp() .

    如果您使用的是jQuery UI,则可以使用该函数,或复制其定义from the source

    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]"
    
  • 7

    虽然您可以使用similar post动态创建RegExp 's (as per the other responses to this question), I' ll回显我的注释:String.replace()的功能形式非常有用,并且在许多情况下减少了对动态创建的RegExp对象的需求 . (这是一种痛苦'因为你必须将RegExp构造函数的输入表示为字符串而不是使用斜杠/ [A-Z] / regexp文字格式)

相关问题