1

I want to replace/delete any text (also with line breaks) that is between 2 javascript comments, but the forward-slashes make me headache.

What I have at the moment, but is not working:

var text="//beginTESTTESTTEST//end";
var regex = "/\//begin+(.)+\//end*/g";
console.log(text.replace(regex,""));

Expected output would be
"//begin//end"

Thank you

2
  • The expected output is that the comments are still there, but the text in between replaced/deleted. Commented Jul 4, 2021 at 14:45
  • 1
    May be: str.replace(/(\/{2}begin)[^]*?(\/{2}end\b)/g, '$1$2'); Commented Jul 4, 2021 at 14:56

2 Answers 2

1

There are a couple of issues:

  • Do not put the regex literal inside a string literal (i.e. do not use single/double quotes or backticks around the /regex_pattern/), it ruins the regex as the slashes become part of the pattern
  • (.)+ makes little sense as the capturing group is placed around a . that matches any char but line break chars, and effectively, you capture the last char from the matched sequence. BUT: we capture what we need to keep, and we just match what we want to discard. Thus, put the (...) only around those parts you want to keeep, //begin and //end and use backreferences in the replacement part to restore these substrings in the result
  • * is greedy, and in case there are more than one match in the string, .* will overmatch across several delimiters, so it is safer to use a lazy version, .*?
  • . does not match line break chars, so it is better to use [^] (only in ECMAScript regex flavor), [\s\S] / [\d\D] / [\w\W], or use . with s flag (in the contemporary ECMAScript 2018+ compliant JS environments)
  • Mind that inside a regex literal, / are "special" and need escaping with \.

So, here are a couple of possible fixes:

var text="//beginTESTTESTTEST//end";
// Capture the parts you need to keep and use backreferences in the replacement
console.log(text.replace(/(\/\/begin)[\w\W]*?(\/\/end)/g, "$1$2"));
// Just match the pattern and use a literal in the replacement
console.log(text.replace(/\/\/begin[\w\W]*?\/\/end/g, "//begin//end"));

Sign up to request clarification or add additional context in comments.

Comments

0

Using Lookahead and Lookbehind :

text.replace(/(?<=\/\/begin)(.*)((?=\/\/end))/gm,'');

1 Comment

It did not work for me @navid ... Thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.