RegEx match URL to contain /wp-content/

I need to check an anchor path for containing /wp-content/ .

For instance, <a href="http://domain.com/wp-content/...">Link1</a>

Read More

In this case the RegExp must match pattern with url and return string in array

['http://domain.com', 'domain.com', 'http://domain.com/wp-content/', '']

In my code I use this but I do something wrong

$('a').live('click', function(e) {
     var host = thisClick.attr('href'),
         pattern = /(?:https?://)?(?:www.)?(.*?)?(/wp-content/)?//,
         matchReg = host.match(pattern);
});

What’s wrong with up line code?

Related posts

Leave a Reply

1 comment

  1. See what happens when you apply your regex:

    1. First character, <, doesn’t match h in (?:https?://)?. Moving on.
    2. Doesn’t match w in (?:www.)?, moving on
    3. DOES match . in (.*?)?
    4. The quantifier will go on as long as it doesn’t match a / or a /wp-content/
    5. You end up with <a href="http:/ matched.

    You can’t make everything optional, or there isn’t any anchor the regex can work on to get to the start of the URL. If you’re trying to always match something in a <a> tag, try:

    /href="(((?:https?://)?(?:www.)?(.*?)?)/wp-content//
    
    • Non optional /wp-content/, that’s your criteria.
    • No additional forward slash after the one from wp-content/
    • First group will capture http://domain.com/wp-content/, second http://domain.com, third domain.com
    • Demo for fun here: http://regex101.com/r/lF5qO7