Ok, I've finally figured this out. It looks like it is too complex to do with just a single RegExp I need multiple!
See it in action Here
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, escapedWord+'[^\\w]', index);
}
}
//word to find ends with non-wordcharacter
else if(regexLastIndexOf(escapedWord, '[^\\w]', 0) == wordtofind.length - 1){
var index = regexIndexOf(subjectString, '[^\\w]'+escapedWord, index);
while(index > 0){
subjectString = subjectString.substring(0, index) + replacement + subjectString.substring(index + myword.length + 1);
index = regexIndexOf(subjectString, escapedWord+'[^\\w]', index);
}
}
//word is normal
else{
var index = regexIndexOf(subjectString,'[^\\w]'+escapedWord+'[^\\w]', index);
while(index >= 0){
subjectString = subjectString.substring(0, index + 1) + replacement + subjectString.substring(index + wordtofind.length + 1);
index = regexIndexOf(subjectString,'[^\\w]'+escapedWord+'[^\\w]', index);
}
}
return subjectString;
}