Simulating REGEX look-behinds in JavaScript
- » Overview
- » Usage & Params
- » Examples
- » Notes
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...
Comments (5)
Marcus Tucker, at 1/03/'11 02:22, said:
Mitya, at 1/03/'11 08:24, said:
Marcus Tucker, at 1/03/'11 13:23, said:
Mitya, at 1/03/'11 13:34, said:
Steven Levithan, at 14/04/'12 22:18, said: