0

I need to remove some text from a big string with start and end label. For example:

...
// THIS IS START
..
..
// THIS IS END
...

Above text is saved in an variable. And I need to remove all texts start with // THIS IS START to // THIS IS END. I know that I can remove them by split the string into lines and parse them line by line. But I am looking for a better solution. Whether I can use regex to achieve this? The difficult part for me is to use variables for start/end labels.

Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523
  • For your last edit please see https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression – revo Aug 05 '18 at 06:49

3 Answers3

1

Use .replace to search for THIS IS START, lazy-repeat any character, up until THIS IS END:

const str = `...
// THIS IS START
..
foo
..
// THIS IS END
...
between
...
// THIS IS START
..
bar
..
// THIS IS END`;
console.log(str.replace(/(\/\/ THIS IS START)[\s\S]+?(\/\/ THIS IS END)/g, '$1\n$2'));

If you don't want to include the // lines either, then don't bother capturing them, and replace with the empty string:

const str = `...
// THIS IS START
..
foo
..
// THIS IS END
...
between
...
// THIS IS START
..
bar
..
// THIS IS END`;
console.log(str.replace(/\s\/\/ THIS IS START[\s\S]+?\/\/ THIS IS END/g, ''));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

This is a fairly simple case. You need to mask your / and make sure to match the "shortest possible" string with the [^]*? expression (.*? does not allow newlines!) between the start and end labels, but otherwise it is straightforward.

Edited, (after hint from @revo):

string.replace(/\/\/ THIS IS START[^]*?\/\/ THIS IS END/g,'')

The character class [^] allows all characters, including newlines etc.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

I think it should be (with gs option)

var str = `
// THIS IS START
..
// THIS IS END`;
console.log(str.replace(/\/\/ THIS IS START\n(.+)\/\/ THIS IS END/gs, "$1"));

https://jsfiddle.net/m8hd1au6/19/

D. Seah
  • 4,472
  • 1
  • 12
  • 20