Last Updated: February 25, 2016
·
892
· kameron

Javascript lookbehind

Javascript regular expressions are a very powerful tool, but they do not come with all the built in niceness that some other languages get to enjoy, such as positive/negative lookbehinds.

Fortunately there is a way to mimic this behavior. Let's say that you want to write a little function to take in an html string and create an anchor tag out of anything string that should be a link (aka starts with http://). The one gotcha here is that you need to be able to check if the piece of the string is already an html anchor tag. This is where the lookbehind comes in handy because we can do this check and process the piece of string as needed.

Alright, here is the code:

makeAnchorTags: function(str) {
    return str.replace(/(<a href=["'])?(http[s]?:\/\/[^\s"']*)/gm,function($0, $1, $2) {
        var link = $2;
        return ($1 !== undefined) ? $0 : '<a href="' + link + '" target="_blank">' + link + '</a>';
    });
}

Alright, now I'll break down what's going on. First the straightforward part, writing the regular expression. We check to see if there is the one or none of a piece of the anchor tag and capture it before looking for the http portion. We then capture the http portion of the link searching until we come across a space, ', or " and we add a global and multiline parameter at the end so we can search the whole string and get multiple matches.

Now the tricky part. Replace can take a callback and we can pass in our captured strings from the regex. We pass in $0 (the whole captured string), $1 (the anchor portion of the string), and $2 (the link/href portion of the string). Since we want the lookbehind to take place on the anchor portion of the string we can simply check if that is defined or not. If it is defined this means we are looking at a properly formed html anchor tag, so we return the whole string ($0). If it is undefined this means there is no anchor tag wrapping our link so we return the link with a proper html anchor tag wrapped around it.

There is much more you can do with this technique than a simple link search! Give it a try yourself and happy coding!