Find the example code for a word in Javascript that does not end in the XX character

  • 2020-03-26 21:24:11
  • OfStack

First, let me state that I spent more than two hours working on regular expressions before writing this article. Sad, sad, sad

As a general idea, let's look at a few other ways to find inserts: I use strings
 
var str = "eattd gebcat gedat jadu geat beu"; 

� example.

1. If you start with "ge", the result should be "gebcat, gedat, geat". Since the word begins 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 += "<br>The result is: " + matchedStr[0]; 
//newStr = newStr.replace(matchedStr[0]); 
wordsArr.push(matchedStr[0]); 
} 
matchedStr = exp1.exec(str); 
} 

2. Words ending in "at" result in "gebcat","gedat","geat". Again, I can put in an array.
 
var exp1 = /w+(atb)/ig; 

3. For words that don't start with "ge", I need another array.
 
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 += "<br>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 don't end in "at". Ok, question. Javascript Regex is weak and does not support inverse loop negation, so it cannot write:
 
var exp1 = /w+(?<!atb)/ig; 

while
 
var exp1 = /w+(?!atb)/ig; 

"At" can't be found on the right side of the end of the word, it's impossible, \b\w is to find the word boundary. I'll do it at a different Angle, find the word that ends in at, and delete it 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 += "<br>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 += "<br>The result is: " + wordsArr; 
} 

OK, done!

Think is gained, do not think is lost.

Related articles: