JavaScript-字符串正则表达式反向引用


93

您可以在JavaScript中像这样反向引用:

var str = "123 $test 123";
str = str.replace(/(\$)([a-z]+)/gi, "$2");

这(很愚蠢)将“ $ test”替换为“ test”。但是想象一下,我想将所得的$ 2字符串传递给一个函数,该函数返回另一个值。我尝试这样做,但没有得到字符串“ test”,而是得到了“ $ 2”。有没有办法做到这一点?

// Instead of getting "$2" passed into somefunc, I want "test"
// (i.e. the result of the regex)
str = str.replace(/(\$)([a-z]+)/gi, somefunc("$2"));

Answers:



34

将函数作为第二个参数传递给replace

str = str.replace(/(\$)([a-z]+)/gi, myReplace);

function myReplace(str, group1, group2) {
    return "+" + group2 + "+";
}

根据mozilla.org,此功能自Javascript 1.3起就存在。


1

使用ESNext,是一个相当虚构的链接替换器,但只是为了展示其工作原理:

let text = 'Visit http://lovecats.com/new-posts/ and https://lovedogs.com/best-dogs NOW !';

text = text.replace(/(https?:\/\/[^ ]+)/g, (match, link) => {
  // remove ending slash if there is one
  link = link.replace(/\/?$/, '');
  
  return `<a href="${link}" target="_blank">${link.substr(link.lastIndexOf('/') +1)}</a>`;
});

document.body.innerHTML = text;


0

注意:先前的答案缺少一些代码。现在是固定的+示例。


我需要一些更灵活的正则表达式替换来解码传入的JSON数据中的unicode:

var text = "some string with an encoded '&#115;' in it";

text.replace(/&#(\d+);/g, function() {
  return String.fromCharCode(arguments[1]);
});

// "some string with an encoded 's' in it"

0

如果您将具有数量不等的反向引用,则参数计数(和位置)也是可变的。该MDN的Web文档描述了一个sepcifing功能替代参数的follwing语法:

function replacer(match[, p1[, p2[, p...]]], offset, string)

例如,使用以下正则表达式:

var searches = [
    'test([1-3]){1,3}',  // 1 backreference
    '([Ss]ome) ([A-z]+) chars',  // 2 backreferences
    '([Mm][a@]ny) ([Mm][0o]r[3e]) ([Ww][0o]rd[5s])'  // 3 backreferences
];
for (var i in searches) {
    "Some string chars and many m0re w0rds in this test123".replace(
        new RegExp(
            searches[i]
            function(...args) {
                var match = args[0];
                var backrefs = args.slice(1, args.length - 2);
                // will be: ['Some', 'string'], ['many', 'm0re', 'w0rds'], ['123']
                var offset = args[args.length - 2];
                var string = args[args.length - 1];
            }
        )
    );
}

您不能在这里使用'arguments'变量,因为它是类型Arguments而没有类型,Array因此它没有slice()方法。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.