JSFiddle - React, Tailwind, and code Playground
HTML
<h2><b>Test String</b></h2>
<div id="basestring"></div>
<br />
<h2><b>Replacing "testword," with "*****"</b></h2>
<div id="result1"></div>
<br />
<h2><b>Replacing "(testword" with "*****"</b></h2>
<div id="result2"></div>
<br />
<h2><b>Replacing "testword" with "*****"</b></h2>
<div id="result3"></div>
<br />
<h2><b>Replacing "(testword," with "*****"</b></h2>
<div id="result4"></div>
JavaScript
function regexIndexOf(mystring, regex, startpos) {
var indexOf = mystring.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
function regexLastIndexOf(mystring, regex, startpos) {
regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
if(typeof (startpos) == "undefined") {
startpos = mystring.length;
} else if(startpos < 0) {
startpos = 0;
}
var stringToWorkWith = mystring.substring(0, startpos + 1);
var lastIndexOf = -1;
var nextStop = 0;
while((result = regex.exec(stringToWorkWith)) != null) {
lastIndexOf = result.index;
regex.lastIndex = ++nextStop;
}
return lastIndexOf;
}
function EscapeRegex(text) {
if (!RegExp.sRE) {
var chars = '/.*+?|()[]{}\\'.split('');
RegExp.sRE = new RegExp('\\'+chars.join('|\\'), 'g');
}
return text.replace(RegExp.sRE, '\\$&');
}
function ReplaceWholeWord(subjectString, wordtofind, replacement){
var escapedWord = EscapeRegex(wordtofind);
//simplest scenaro, word to find has non-word characters at begining and end - do basic replace
if(regexIndexOf(escapedWord, '[^\\w]', 0) == 0 && regexLastIndexOf(escapedWord, '[^\\w]', 0) == wordtofind.length - 1){
subjectString = subjectString.replace(new RegExp(escapedWord, 'g'), replacement);
}
//word to find begins with non-wordcharacter
else if(regexIndexOf(escapedWord, '[^\\w]', 0) == 0){
var index = regexIndexOf(subjectString, escapedWord+'[^\\w]', index);
while(index > 0){
subjectString = subjectString.substring(0, index) + replacement + subjectString.substring(index + wordtofind.length);
index = regexIndexOf(subjectString,...