Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 790
Shamoon Avatar asked Nov 28 '22 06:11

Shamoon


2 Answers

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;
like image 104
Tushar Avatar answered Apr 11 '23 17:04

Tushar


For the encoding, you can use encodeURIComponent:

var links = document.querySelectorAll('a');
for(var i=0; i<links.length; ++i)
  links[i].href = encodeURIComponent(links[i].href);
<a href="http://example.com/test this now">Stuff</a>
More stuff
<a href="http://example.com/more?stuff goes here">more</a>

If you only have a HTML string instead of DOM elements, then use don't use regular expressions. Parse your string with a DOM parser instead.

var codeString = '<a href="http://example.com/test this now">Stuff</a>\nMore stuff\n<a href="http://example.com/more?stuff goes here">more</a>';
var doc = new DOMParser().parseFromString(codeString, "text/html");
var links = doc.querySelectorAll('a');
for(var i=0; i<links.length; ++i)
  links[i].href = encodeURIComponent(links[i].href);
document.querySelector('code').textContent = doc.body.innerHTML;
<pre><code></code></pre>

And note that if you encode the URL entirely, it will be treated as a relative URL.

like image 28
Oriol Avatar answered Apr 11 '23 16:04

Oriol