Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace everything between two words including this words

How to change this tt /* a */ pp /* b */ dd to

tt dd

this not including a and b link

var test = "tt /* a / pp / b */ dd"; //var res = "tt dd";

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is it simple with regexp?

>Solution :

If you want to remove something between two things, including those things, regex could do the trick pretty easily:

const str = 'tt /* a */ pp /* b */ dd';
const start = '/\\* a \\*/';
const end = '/\\* b \\*/';

const pattern = new RegExp(`${start}.*${end}`, 'g');

const result = str.replace(pattern, '');

console.log(pattern);
console.log(result);

There are two gotchas however.

The first is from your choice of delimiter. Since it has a * in it, which has special meaning in regex, you need to be sure to escape it. If you choose a delimiter without characters special to regex, you don’t have to do that.

The other gotcha isn’t a gotcha so much as it is a requirement issue. You wanted tt dd, but you’ll get tt dd as you describe it (two spaces), since both spaces are outside of your delimiters.

There are a couple of ways to deal with that. One could be to just replace two or more spaces with one space:

const str = 'tt  dd';
const result = str.replace(/\s+/g, ' ');

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading