-2

How to replace a string between two string in javascript

StartLine = `/*TESTSTART*/`;
Endline   = `/*TESTEND*/`;

OriginalContent = `/*TESTSTART*/ 
testing 
not 
working
/*TESTEND*/`;    
var e = OriginalContent .replace(/(StartLine)[\s\S]*?(Endline)/,' it's 
working
fine');    

OUTPUT = `/*TESTSTART*/ 
it's 
working
fine
/*TESTEND*/`

1) How to check if the string contains / in regular exp? 2) if I stored sting in one variable, how can I use this variable in regular exp?

franiis
  • 1,378
  • 1
  • 18
  • 33
Aziza Azi
  • 19
  • 1

1 Answers1

0

You can escape a / character with a backslash \ if you're using / to start your regular expression. But in this case, since you want to include the value of a variable in your regular expression, you should use a string to represent a regex instead, in which case there is no need to escape / but you should escape other special regex characters such as * with two backslashes, and you can simply concatenate the variable with the other string literals and variables to form the full regex:

StartLine = '/\\*TESTSTART\\*/';
Endline = '/\\*TESTEND\\*/';

...

var e = OriginalContent.replace(StartLine + '[\s\S]*?' + Endline, "it's 
working
fine");
blhsing
  • 91,368
  • 6
  • 71
  • 106