0

My goal is to find all strings that match www.website.com or website.com.

If that address is not currently linked, then replace any matched string with...

<a href="https://www.website.com">www.website.com</a>

or

<a href="https://www.website.com">website.com</a>

Here's what I have so far...

document.body.innerHTML = document.body.innerHTML.replace(/website.com/g, '<a href="https://www.website.com">www.website.com</a>');
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam minima, www.website.com suscipit expedita excepturi laboriosam website.com nesciunt accusantium quae placeat ex nostrum esse corrupti nisi hic velit commodi molestiae.</p>

But, I can't seem to account for addresses that already have the www in front of it.

Millhorn
  • 2,953
  • 7
  • 39
  • 77
  • 2
    How about `replace(/(www\.)?website\.com/g, '$&')` – Phil May 18 '21 at 23:41
  • 1
    when you replace website.com, it also replaces www.website.com, and then displays www.www.website.com so you need to make 2 replace, one for with www, one without. The one without can be done with a regex. – Pierre May 18 '21 at 23:42
  • Thanks both of you. I just needed more regex. – Millhorn May 18 '21 at 23:43

1 Answers1

0

You can make a generic regex as

const regex = /(www.)?(\w+|\d+)+(\.com)/;

demo

const str1 = "website.com";
const str2 = "www.website.com";
const str3 = "www.google.com";
const str4 = "www.regex101.com";
const regex = /(www.)?(\w+|\d+)+(\.com)/;

const result1 = str1.replace(regex, `<a href="https://www.$2.com">$1$2$3</a>`);
const result2 = str2.replace(regex, `<a href="https://www.$2.com">$1$2$3</a>`);
const result3 = str3.replace(regex, `<a href="https://www.$2.com">$1$2$3</a>`);
const result4 = str4.replace(regex, `<a href="https://www.$2.com">$1$2$3</a>`);

console.log(result1);
console.log(result2);
console.log(result3);
console.log(result4);
DecPK
  • 24,537
  • 6
  • 26
  • 42