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

135
Views
Replace line comment(//) to block comment(/*) regex JS

I want to get a regex to replace all line comments to block comments, but I want to return only legal js comments and not // that is part of a string for that I have to detect if // is in quotes and not replace it.

Now I got something like this /"(.*?\/\/.*?)"/, but it replaces the opposite - all // in quotes and not the ones without.

// Change heading:

should match

document.getElementById("myH").innerHTML = "My First //Page";  

shouldn't match

document.getElementById("myP").innerHTML = "My first paragraph."; // Change paragraph:;

should match

console.log("some important info //shouldn't replace"); // this is important info

In this case, valid comment should match, but comment inside quotation marks shouldn't.

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

0

Match the comments with /(?:(?=["'][^"']*$)|(?=^[^"']*\/\/.*$))(.*?)\/\/(.*)/gm and replace with $1/*$2*/.

let code = `// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";  // Change paragraph:

console.log("some important info //shouldn't replace"); // this is important info
console.log('some important info //should not replace'); // this is important info`;

code = code.replace(/(?:(?=["'][^"']*$)|(?=^[^"']*\/\/.*$))(.*?)\/\/(.*)/gm, "$1/*$2*/");
console.log(code);

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!