/*
* BEGIN EXAMPLES
*/
var text = 'A Cats Catalog of Cat Catastrophes and Calamities';
/***
* EXAMPLE 1: negative lookahead assertion logic
***/
var newString = text.split(/\s/);
for (var i in newString) {
var word = newString[i];
if (
// we'll replace the word Cat under these conditions:
word.search(/Cat/) == 0 && // *if* word begins with Cat
word != 'Catalog' && // *but* is not Catalog
word != 'Catastrophes' // *and* is not Catastrophes
) {
// we'll replace the word Cat with Human
newString[i] = (word.replace('Cat', 'Human'));
}
}
alert(newString.join(' '));
// -A Humans Catalog of Human Catastrophes and Calamities
/***
* EXAMPLE 2: the simpler version
***/
var pattern = /(Cat(?!alog|astrophes))/g;
alert(text.replace(pattern, 'Human'));
// -A Humans Catalog of Human Catastrophes and Calamities
/*
* END EXAMPLES
*/
example 1 === example 2. it may appear from this point forward it'll
be safe to assume my understanding of a negative look ahead may be
correct. problem is, I feel my understanding may be flawed. here is
why...
I always knew about positive/negative look aheads but didn't truly
understand them. Wrox Professional JavaScript sort of cleared it up
for me *but* upon deciding to sharpen my skills on my own, I came
across a peculiar problem.
Does being greedy work with them?
e.g., I created this problem entirely on my own. I didn't mean to, it
just ended up that way. my idea was to match \d+\.\d+ but not if it
was followed by \.\d+ .
here's an example:
var nla = /(\d+\.\d+(?!\.\d))/; // my negative look ahead
var txt = 'euphoria 72.21.330';
alert(nla.exec(txt)[1]); // -72.2 (completely unexpected)
what did I expect? nothing. null, nada. I am not at all interested in
the dozens of other possible solutions. I am most interested in
understanding this problem. I need enlightenment and very much
appreciate any insight on it!