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

发布于 2024-08-25 04:18:21 字数 416 浏览 6 评论 0原文

你可以在 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"));

You can backreference like this in JavaScript:

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

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?

// 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"));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

慕巷 2024-09-01 04:18:21

像这样:

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

Like this:

str.replace(regex, function(match, $1, $2, offset, original) { return someFunc($2); })
清引 2024-09-01 04:18:21

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

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

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

根据 mozilla.org

Pass a function as the second argument to 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.

望她远 2024-09-01 04:18:21

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

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

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;

陪我终i 2024-09-01 04:18:21

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


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

var text = "some string with an encoded 's' in it";

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

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

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:

var text = "some string with an encoded 's' in it";

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

// "some string with an encoded 's' in it"
尘世孤行 2024-09-01 04:18:21

如果反向引用的数量可变,那么参数计数(和位置)也是可变的。 MDN 网络文档描述将函数指定为替换参数的以下语法:

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() 方法。

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

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 Arguments and no of type Array so it doesn't have a slice() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文