preg_replace_callback for Javascript

mattkenefick

Matt Kenefick

Posted on May 5, 2021

preg_replace_callback for Javascript

I had need for something like this recently so I thought I'd share in case someone else needs it.

function preg_replace_callback(pattern, callback, string) {
    [...string.matchAll(pattern)].forEach(value => {
        string = string.replace(value[0], callback(value));
    });

    return string;
}


let foo, result;

// Capitalize first letters
foo = 'The quick brown fox jumped over the lazy dog.';
result = preg_replace_callback(/\s([a-z])/gm, matches => matches[0].toUpperCase(), foo);
console.log(result);
// Result: "The Quick Brown Fox Jumped Over The Lazy Dog."

// Double found numbers
foo = 'Their ages are 12, 15, and 22.';
result = preg_replace_callback(/([0-9]+)/gm, matches => matches[0] * 2, foo);
console.log(result);
// Result: "Their ages are 24, 30, and 44."
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
mattkenefick
Matt Kenefick

Posted on May 5, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related