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.

3 Answers 3

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

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

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

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

Comments

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 */

Comments

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

Comments

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.