A brief explanation: I have a string which contains sentences. I want to change a specific word to Foo+word+Bar For example the word that i want to change in this case is "this". "this" should only be changed when it stands alone for example:
HellothisOk, HelloThis thisthis and ThisOk
should not be changed, while:
thiS, "this" this!!! this %this!? this? this. THIS
Should change.
The code below works perfect (from this answer):
const str = 'Hello This is a test string this is a test THISthis is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible. this??? this! "this "this" this" HellothisOk HelloThis ThisOk';
const result = str.replace(/(?<!\w)(this)(?!\w)/gi, "Foo$1Bar");
console.log(result)
But when want to change "this" to a variable like this:
const str = 'Hello This is a test string this is a test THISthis is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible. this??? this! "this "this" this" HellothisOk HelloThis ThisOk';
const variable = "this";
const result = str.replace(new RegExp('(?<!\w)('+variable+')(?!\w)', 'gi'), "Foo$1Bar");
console.log(result);
I don't get the same output and I don't understand why.
You don't need to append and prepend / when putting a RegExp in a string. Also make sure to escape any backslashes.
const str = 'Hello This is a test string this is a test THISthis is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible. this??? this! "this "this" this" HellothisOk HelloThis ThisOk';
const variable = "this";
const result = str.replace(new RegExp('(?<!\\w)('+variable+')(?!\\w)', 'gi'), "Foo$1Bar");
console.log(result);