0

I wrote a RegExp to grab and encode URLs in JavaScript. This works fine but, it introduced a bug into my app. I have a span Element which is used to display Emojis like this:

<span style="background:url(http://localhost/res/emo/face/E004.png)"></span>

Now, I'm using this Regular Expression to grab and convert anything URL into actual HTML clickable links:

/((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/ig

This ended up encoding the emoji URL into a clickable link. Can anyone adjust that Code to Ignore URLs inside Elements or embedded Objects???

Please I need help!

This is the code:

var urlRegex = /((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/ig;
return txt.replace(urlRegex, function (url) {
  var hyperlink = url;
  if(!hyperlink.match('^https?:\/\/')) {
    hyperlink = 'http://' + hyperlink;
  }

  return `<a href="/?away=${encodeURIComponent(hyperlink)}&ref_component=hyperApp" target="_blank" rel="noopener noreferrer">${url}</a>`;
});

I don't that the URLS inside

<span style="background:url(http://localhost/res/emo/face/E004.png)"></span>

were touched.

Bhad Guy
  • 80
  • 7
  • We'd probably have to see that code to make any recommendations. However, without seeing it I would recommend adding a class to all elements that you don't want to be considered. With that in place you can set up some filtering to encode only the elements you want to consider. – GenericUser Jun 14 '21 at 20:26
  • can you show the code that runs the regex? is it cycling through each element? How are you impolementing that? – Kinglish Jun 14 '21 at 20:28
  • So, I have added the code that encodes the URLs – Bhad Guy Jun 14 '21 at 20:37

1 Answers1

0

You would need to use negative look behind, which has limited support in JavaScript. (see here https://stackoverflow.com/a/50434875/6853740)

Simply adding negative look behind to your existing regex still doesn't work as expected:

((?<!url\()(https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?) still matches "E004.png" in your example. Even other URL regexs from this post (What is the best regular expression to check if a string is a valid URL?) also match that. You may need to consider only looking for links that start with http:// or https:// which may help you recraft a regex that will only match full URLs.

Kenny DiFiore
  • 151
  • 1
  • 6