JavaScript Negative Lookbehind

I've looked through numerous other questions up here surrounding a negative lookbehind for JavaScript but I can't seem to mimic them. I have the following Regex:

\b((?:http[s])?\S+\.\S+\.(?:\S+\.?){1,4})(?<[email protected])\b` 

and the basis of this Regex is it matches web addresses like:

  • www.msn.com
  • or http://www.msn.com
  • or https://www.google.com
  • or http://msdn.microsoft.com.

However, it also matches [email protected] because of the numerous domain names following the @ sign. I need to perform a negative lookbehind for that @ sign.

Hopefully somebody can give me a hand!

UPDATE

Updating to include the replacement string that I'm using to create the hyperlink out of the matched text.

replace(webLinkPattern, "<a href=\"http://$2\" target=\"_blank\" onclick=\"preventDualEditing(event)\">$2</a>");

UPDATE 2 - ANSWER

ts = ts.replace(webLinkPattern, function (url) {
    if (url.indexOf('@') != -1) {
        return url;
    }

    return url.replace(webLinkPattern, "<a href=\"http://$&\" target=\"_blank\" onclick=\"preventDualEditing(event)\">$&</a>");
});

Answers:

Answer

JavaScript doesn't support lookbehind assertions, so you'll have to handle this in your own code. One option is simply to include the @ in the result, and then discard the match if the @ is there:

replace(/(?:\b|@)(?:https?)?\S+\.\S+\.(?:\S+\.?){1,4}\b/,
        function(url) {
          if(url.indexOf('@') > -1)
            return url;
          return '<a href="' + url + ' target="_blank"' +
                 ' onclick="preventDualEditing(event)">' + url + '</a>';
        }
       );

Alternatively, you can check for a preceding @ in the callback, even without including it in url:

replace(/\b(?:https?)?\S+\.\S+\.(?:\S+\.?){1,4}\b/,
        function(url, pos, str) {
          if(pos > 0 && str.charAt(pos - 1) == '@')
            return url;
          return '<a href="' + url + ' target="_blank"' +
                 ' onclick="preventDualEditing(event)">' + url + '</a>';
        }
       );

(Note that I've also changed http[s] to https?, which is what you meant. http[s] is the same as https, since [s] is a character class matching any character that's s.)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.