Una breve explicación: tengo una cadena que contiene oraciones. Quiero cambiar una palabra específica a Foo+word+Bar Por ejemplo, la palabra que quiero cambiar en este caso es "esto". "esto" solo debe cambiarse cuando está solo, por ejemplo:
hola estook, hola esto esto esto y estook
no debe cambiarse, mientras que:
¡¡¡esto esto esto!!! este % esto!? ¿este? este. ESTE
Deben cambiar.
El siguiente código funciona perfecto (de esta respuesta ):
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)Pero cuando quiera cambiar "esto" a una variable como esta:
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);No obtengo el mismo resultado y no entiendo por qué.
No necesita agregar y anteponer / al colocar un RegExp en una cadena. También asegúrese de escapar de cualquier barra invertida.
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);