Pergunta

Você pode fazer backreference como esta em JavaScript:

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

Isso (bastante bobo) substituiria "$ test" pelo "teste". Mas imagine que eu gostaria de passar a sequência resultante de US $ 2 em uma função, que retorna outro valor. Eu tentei fazer isso, mas em vez de obter a string "teste", recebo "$ 2". Existe uma maneira de conseguir isso?

// 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"));
Foi útil?

Solução

Assim:

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

Outras dicas

Passar uma função como o segundo argumento para replace:

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

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

Essa capacidade existe desde o JavaScript 1.3, de acordo com mozilla.org.

Usando o esNext, um substituto de links bastante dummy, mas apenas para mostrar como funciona:

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;

Observação: A resposta anterior estava faltando algum código. Agora é o exemplo fixo +.


Eu precisava de algo um pouco mais flexível para um regex substituir para decodificar o unicode nos meus dados JSON de entrada:

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"

Se você tiver uma quantidade variável de referências de fundo, a contagem de argumentos (e os lugares) também é variável. o MDN Web Docs Descreva a sintaxe de folga para sepcifrar uma função como argumento de substituição:

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

Por exemplo, pegue estas expressões regulares:

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

Você não pode usar a variável 'argumentos' aqui porque é do tipo Arguments e nenhum tipo Array Então não tem um slice() método.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top