Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda