rosia
rosia

Reputation: 229

Javascript - how can I make links from text excluding any already made link?

How can I make as link from a url found in text, but excluding any already made link found? Can you help with the proper regex?

  function makeurl(text) {
  var urlRegex = /(https?:\/\/[^\s]+)/g;
  return text.replace(urlRegex, function(url) {
    return '<a href="' + url + '">' + url + '</a>';
  })
}

var check = 'Hello <a href="https://www.xyyyyy.co">cick here</a> to visit our website http://google.x';

console.log (makeurl(check) )

https://jsfiddle.net/9L30zotx/

I want to change only http://google.x but leave as is the already made html for www.xyyyyy.co

Upvotes: 1

Views: 411

Answers (2)

vrintle
vrintle

Reputation: 5586

If the anchor text isn't a url itself, then you can easily parse out the HTML content, and then you'll have only pure text.

Try the following code,

function makeurl(text) {
  var urlRegex = /(https?:\/\/[^\s]+)/g;
  document.body.innerHTML = text; // taking document.body as example
  text = document.body.innerText;
  
  return text.replace(urlRegex, function(url) {
    return '<a href="' + url + '">' + url + '</a>';
  });
}

var check = 'Hello <a href="https://www.xyyyyy.co">click here</a> to visit our website http://google.x';

console.log(makeurl(check))

Upvotes: 0

WhyW0rry
WhyW0rry

Reputation: 11

Maybe you can check if there is a space before the link (or the start in case the link is at the beginning of the text) using ([\s]|^) at the beginning of your regex (/([\s]|^)(https?:\/\/[^\s]+)/g).

Upvotes: 1

Related Questions