0

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.

4
  • 2
    What if we add a check that we are not inside <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 Commented Apr 24, 2015 at 12:08
  • Exactly.. that would be a better approach.. Commented Apr 24, 2015 at 12:09
  • Perhaps, *:not([href]) can do as well in the selector. Commented Apr 24, 2015 at 12:20
  • Thanks - I have implemented the regex and this so far seems to work great - will continue testing Commented Apr 24, 2015 at 12:31

1 Answer 1

1

You can change your selector to exclude anchors with no href tag like this:

:not([href])

so then your selector becomes:

var httpSelector = 'a:not([href]).single-ai1ec_event ...';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.