First, let me state that I spent over 2 hours playing with regular expressions before writing this article. Sad~sad~sad~
According to the general idea, let’s take a look at several other insertion methods: I use the string
var str = "eattd gebcat gedat jadu geat beu";
is an example.
1. If it starts with "ge", the result should be "gebcat, gedat, geat". Since the word starts with "ge", I can put in a new array for later use.
var exp1 = /bgew /ig;
var matchedStr = exp1.exec(str);
while (matchedStr != null && matchedStr.index < str.length) {
if (matchedStr[0] != null) {
inv.innerHTML = "
The result is: " matchedStr[0];
//newStr = newStr.replace(matchedStr[0]);
wordsArr.push(matchedStr[0]) ;
}
matchedStr = exp1.exec(str);
}
2. For words ending with "at", the result is "gebcat", "gedat", "geat". Likewise, I can put in an array.
var exp1 = /w (atb)/ig;
3. For words that do not start with "ge", I need another array to store them.
var exp1 = /b(?!ge)w / ig;
var wordsArr = new Array();
var matchedStr = exp1.exec(str);
while (matchedStr != null && matchedStr.index < str.length) {
if (matchedStr[0] != null) {
inv.innerHTML = "
The result is: " matchedStr[0];
newStr = newStr.replace(matchedStr[0]);
wordsArr.push(matchedStr[0]);
}
matchedStr = exp1.exec(str);
}
//wordsArr = newStr.split(" ") ;
for (var i = 0; i < wordsArr.length;) {
if (wordsArr[i] == "undefined") {
wordsArr.splice(i,1) ;
} else
i
}
4. Words that do not end with "at", well, here comes the problem. Regex in Javascript is relatively weak and does not support reverse lookaround negation, so it cannot be written:
var exp1 = /w (?
and
var exp1 = /w (?!atb)/ig;
The right side of the end of the word in the meaning of
cannot be " at", that is impossible, bw is to find word boundaries. I write it from another angle, find the word ending with at, and delete the word from the original string. Then put in a new array.
function RegularExpTest() {
var inv = document .getElementById("RegexTest");
var str = "eattd gedbcat gedat jadu geat beu";
var newStr = str;
var exp1 = /w atb/ig;
var wordsArr = new Array();
var matchedStr = exp1.exec(str);
while (matchedStr != null && matchedStr.index < str.length) {
if (matchedStr[0] ! = null) {
inv.innerHTML = "
The result is: " matchedStr[0];
newStr = newStr.replace(matchedStr[0]);
}
matchedStr = exp1.exec(str);
}
wordsArr = newStr.split(" ");
for (var i = 0; i < wordsArr.length;) {
if (wordsArr[i] == "undefined") {
wordsArr.splice(i,1);
} else
i
}
inv.innerHTML = "
The result is: " wordsArr;
}
OK, done!
Think and you will get; if you don’t think, you will not get.