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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2447915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:23:55  来源:igfitidea点击:

JavaScript - string regex backreferences

javascriptregexbackreference

提问by quano

You can backreference like this in JavaScript:

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

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

This would (quite silly) replace "$test" with "test". But imagine I'd like to pass the resulting string of $2 into a function, which returns another value. I tried doing this, but instead of getting the string "test", I get "$2". Is there a way to achieve this?

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

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

回答by SLaks

Like this:

像这样:

str.replace(regex, function(match, , , offset, original) { return someFunc(); })

回答by Sean

Pass a function as the second argument to replace:

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

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

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

This capability has been around since Javascript 1.3, according to mozilla.org.

mozilla.org 称,此功能自 Javascript 1.3 以来一直存在。

回答by vdegenne

Using ESNext, quite a dummy links replacer but just to show-case how it works :

使用 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;

回答by 7ochem

If you would have a variable amount of backreferences then the argument count (and places) are also variable. The MDN Web Docsdescribe the follwing syntax for sepcifing a function as replacement argument:

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

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

For instance, take these regular expressions:

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

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

You can't use 'arguments' variable here because it's of type Argumentsand no of type Arrayso it doesn't have a slice()method.

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

回答by Hymansonkr

Note:Previous answer was missing some code. It's now fixed + example.

注意:上一个答案缺少一些代码。现在已修复 + 示例。



I needed something a bit more flexible for a regex replace to decode the unicode in my incoming JSON data:

我需要一些更灵活的正则表达式替换来解码传入 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"