在.replace()中创建一个函数

时间:2015-06-19 04:38:20

标签: javascript regex

我有以下使用正则表达式的代码:

var mystring = "<<cool>> <<stuff>>"
var regexString = /<<([^\:]{0,})>>/gi

mystring.replace(regexString, "$1")

我希望能够根据我在捕获组上返回的文本替换字符串。类似的东西:

var mystring = "<<cool>> <<stuff>>"
var regexString = /<<([^>]{1,})>>/gi

mystring.replace(regexString, function(var0) { //var0 being the text from the capture group

    if(var0 == "cool") {
        console.log("got cool")

    } else {
        console.log("didn't get cool")
    }
})

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

是的,您绝对可以将函数用作.replace()的第二个参数。例如:

mystring.replace(regexString, function(match, group1) { 
    // do anything with group1 here
});

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace