Shamoon Shamoon - 7 months ago 22
Javascript Question

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

My text is something like:

<a href="http://example.com/test this now">Stuff</a>

More stuff

<a href="http://example.com/more?stuff goes here">more</a>


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

How would I go about this?

UPDATE
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="http%3A%2F%2Fexample.com%2Ftest%20this%20now">Stuff</a>

More stuff

<a href="http%3A%2F%2Fexample.com%2Fmore%3Fstuff%20goes%20here">more</a>

Answer

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="http://example.com/test this now">Stuff</a>';

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

var str = `<a href="http://example.com/test this now">Stuff</a>

More stuff

<a href="http://example.com/more?stuff goes here">more</a>`;

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

console.log(str);
document.body.textContent = str;