Home & blog  /  Scripts  /  view post  /

Simulating REGEX look-behinds in JavaScript

Overview

This script simulates look behind assertions (LBAs) in JavaScript, which are not natively supported in the language's implementation of regular expression. It defines three methods: match2 and replace2 (of the String object), and test2 (of the RegExp object).

Usage & Params

Each of the three methods works like its native counterpart, except you can pass an additional argument - the LBA. Specified as a string, these take the form of LBAs in PHP, i.e. (?<=pattern) for positive and

Examples

Using the demo string "scary crocodile; cute puppy; scary lion; cute kitten"...

1) ...match all scary animals:

2) ...replace all scary animals in the above string with 'monster':

3) ...match all words NOT preceded by 'scary':

Here's the code behind these examples:

1//match with positive LBA

2alert('scary crocodile; cute puppy; scary lion; cute kitten'.match2(/[a-z]+/ig, '(?<=scary )'));

3//replace with positive LBA

4alert('scary crocodile; cute puppy; scary lion; cute kitten'.replace2(/[a-z]+/ig, 'monster', '(?<=scary )'));

5//match with negative LBA

6alert('scary crocodile; cute puppy; scary lion; cute kitten'.match2(/[a-z]+/ig, '(?

Notes

To follow...

post new comment

Comments (5)

Marcus Tucker, at 1/03/'11 02:22, said:
Unfortunately your examples don't work in Chrome 9, instead I see alert() dialogs which only contain "null".
Mitya, at 1/03/'11 08:24, said:
Marcus - this is now fixed. Turns out there's a bug in Chrome and Safari (i.e. webkit) which says that instances of the RegExp construction are in fact functions, not objects. Bizarre. Now fixed - thanks for spotting this. I was guilty of assuming Chrome would play ball!
Marcus Tucker, at 1/03/'11 13:23, said:
Aha! Interesting... just read your new post about it, which I spotted via RSS... :)

BUT I didn't receive an email notification that you'd replied to me here... :(

Admittedly this comment form doesn't suggest that I should/would receive notifications but you're (potentially) capturing an email address and it's rare indeed to have a comments system which doesn't emit notification of replies... how else would I know unless I remembered to check back at some point in the future?

I've posted other comments on your articles before an never heard back, perhaps this is why?
Mitya, at 1/03/'11 13:34, said:
Yeah I take your point completely. The thing is I like re-inventing wheels; I could have plugged in an existing comments system and had full functionality, but I built my own. Notification functionality is on the list of things to do (along with start writing some tutorials, re-organise the tagging system, etc etc, urgh...).

At your prompting I think I'll make notifications a priority. Expect it in the next couple of weeks :)
Steven Levithan, at 14/04/'12 22:18, said:
I've posted a more robust version of this that relies on XRegExp at https://gist.github.com/2387815