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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.