Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
new RegExp doesnt seem to work the same as without

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!