0

I need to find a regular expression for replace the commentaires in my js files. What i want is transform all line like this :

 //it's a commentaire

into this

 /* it's a commentaire */

Because i try to optimize my files, and there are issues i think it's come from this. I use php function file_get_content, and it create a string in one line, so all the string become a commentaire causse of the syntax.

user3415011
  • 195
  • 1
  • 2
  • 11

3 Answers3

2
\/\/([^\n]*)

You can try this.Replace by /* $1 */.See demo.

http://regex101.com/r/dK1xR4/9

vks
  • 67,027
  • 10
  • 91
  • 124
0

You could try the below regex to match the strings which starts with // upto the end of the line. In multiline mode, dot would match any character but not of newline character. So you could use .* to match all the following characters and putting the brackets around (.*) would turn the matches into captures.

\/\/(.*)

Replace the matched strings by /* $1 */

DEMO

> var s = "foo //it's a commentaire".replace(/\/\/(.*)/g, "/* $1 */")
undefined
> console.log(s)
foo /* it's a commentaire */
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

If you wanna be on the safe side, you wanna account for this stuff:

<script type="text/javascript">
  var var1 = prompt('Which character does line-escapes?', '//');
</script>

Which isn't a comment because it's inside of a string. I made a post about just this over here. So what you wanna do is use the regex from that answer and inspect the content to see if you're dealing with a line-comment. Easiest way to do that is put the one you want in a capture group:

(\/\/([^\n]*)(?:\n|$))|(['"])(?:(?!\3|\\).|\\.)*\3|\/(?![*/])(?:[^\\/]|\\.)+\/[igm]*|\/\*(?:[^*]|\*(?!\/))*\*\/

Now, if capture group 1 is not empty, replace it with /*$2*/. Otherwise, don't do anything (or replace it with the entire match, effectively not changing anything.

Regular expression visualization

Debuggex Demo

Community
  • 1
  • 1
asontu
  • 4,548
  • 1
  • 21
  • 29