Shamoon Shamoon - 1 year ago 52
Javascript Question

How can I replace everything inside an href with JavaScript regex?

My text is something like:

<a href=" this now">Stuff</a>

More stuff

<a href=" goes here">more</a>

I want to replace what's inside the
with a function that will URL Encode just the URL portion.

How would I go about this?

Here's what I've tried:

postdata.comment.content = postdata.comment.content.replace(/href=\"(.+?)\"/g, function(match, p1) {
return encodeURI(p1);

Does not do what I would have hoped.

Expected result is:

<a href="">Stuff</a>

More stuff

<a href="">more</a>

Answer Source

The regex is matching the complete attribute href="....", however, the replacement is only done by the encoded URL and use encodeURIComponent() to encode complete URL.

var string = '<a href=" this now">Stuff</a>';

string = string.replace(/href="(.*?)"/, function(m, $1) {
    return 'href="' + encodeURIComponent($1) + '"';
    //      ^^^^^^                     ^

var str = `<a href=" this now">Stuff</a>

More stuff

<a href=" goes here">more</a>`;

str = str.replace(/href="(.*?)"/g, (m, $1) => 'href="' + encodeURIComponent($1) + '"');

document.body.textContent = str;