I need to wrap href around matched urls within an imported string - however in some cases the urls already have the href attribute set therefore they do not need wrapping. My code at this early stage is as follows
if(jQuery('.single-ai1ec_event')) {
var httpSelector = '.single-ai1ec_event .entry-content, .single-ai1ec_event .p-location';
var searchText = jQuery(httpSelector).text();
var expression = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var urls = searchText.match(expression);
var wrappedUrl;
if (urls) {
for (var i = 0, il = urls.length; i < il; i++) {
jQuery(httpSelector).html(function () {
wrappedUrl = wrap(urls[i]);
jQuery(this).html(jQuery(this).html().replace(urls[i], wrappedUrl));
});
}
}
}
function wrap(str) {
return '<a href="' + str + '" target="_blank">' + str + '<\/a>';
}
I am currently looking for a way to exclude wrapping urls that aleady have the href attribute set but without much success.
<a>tag:var expression = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?(?!(?:[^>]*?>)?[^<]*?<\/a>)/gi;? See regex101.com/r/oZ7jE4/3*:not([href])can do as well in the selector.