13

There is some string (for example, 's'):

import 'lodash';
// TODO import jquery
//import 'jquery';

/*
Some very important comment
*/

How can I remove all comments from 's' string? Should I use some Regexp for it? I don't know.

malcoauri
  • 11,904
  • 28
  • 82
  • 137

6 Answers6

23

The one from @MarcoS won't work in several cases...

Below is my solution:

str.replace(/\/\*[\s\S]*?\*\/|(?<=[^:])\/\/.*|^\/\/.*/g,'');

Removing comments from a string:

function removeComments(string){
    //Takes a string of code, not an actual function.
    return string.replace(/\/\*[\s\S]*?\*\/|(?<=[^:])\/\/.*|^\/\/.*/g,'').trim();//Strip comments
}
const commentedcode = `
alert('hello, this code has comments!')//An alert
/* A block comment here */
// A single line comment on a newline
`;
console.log(removeComments(commentedcode));

Demo:

regexp examples

EDIT: I changed the formula to avoid issues with links (see comment)

AymKdn
  • 3,327
  • 23
  • 27
7

If you want to use a RegExp, you could use this one:

/(\/\*[^*]*\*\/)|(\/\/[^*]*)/

This should strip both // ... \n style comments and /* ... */ style comments.

Full working code:

var stringWithoutComments = s.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)/g, '');
console.log(stringWithoutComments);

Test with multiline strings:

var s = `before
/* first line of comment
   second line of comment */
after`;
var stringWithoutComments = s.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)/g, '');
console.log(stringWithoutComments);

outputs:

before

after
MarcoS
  • 17,323
  • 24
  • 96
  • 174
5

console.log(`

     var myStr = 'я! This \\'seems\\' to be a // comment'; // but this is actually the real comment.
    /* like this one */ var butNot = 'this "/*one*/"'; // but this one and /* this one */
    /* and */ var notThis = "one '//but' \\"also\\""; /* // this one */
    `
    
    // 1) replace "/" in quotes with non-printable ASCII '\1' char
    .replace(/("([^\\"]|\\")*")|('([^\\']|\\')*')/g, (m) => m.replace(/\//g, '\1'))
    
    // 2) clear comments
    .replace(/(\/\*[^*]+\*\/)|(\/\/[^\n]+)/g, '')
    
    // 3) restore "/" in quotes
    .replace(/\1/g, '/')

);
Abdullah
  • 968
  • 12
  • 17
  • doesn't handle comments with nothing after them, such as `//` on a line by itself, but I really like the support for ignoring comments inside quotes. If you replace your step two, with the accepted answer, this is superior. – phyatt Oct 13 '20 at 01:03
1

You can use this RegEX to match all comments (Supporting Russia Symbols. | Latin or Cyrillic | ).

(\/\*[\wа-я\'\s\r\n\*]*\*\/)|(\/\/[\wа-я\s\'\;]*)|(\<![\-\-\s\wа-я\>\/]*\>)

RegEX Parts :

Part1: (\/\*[\wа-я\'\s\r\n\*]*\*\/) for comments style: /*   .....   */ 

Part2: (\/\/[\wа-я\s\'\;]*)         for comments style: //   .....

Part3: (\<![\-\-\s\wа-я\>\/]*\>)    for comments style: <!-- .....  -->

Updated Regex101 DEMO

Updated JsFiddle DEMO , Supporting Russia symbols in comments


textarea{
  width:300px;
  height:120px;
}
<textarea id="code">
import 'lodash';
// TODO импортируем auth provider
//import 'jquery';

/*
Some very important comment
*/
</textarea>
<br />
<button onclick="removeAllComments()">Remove All Comments</button>

<script>
    function removeAllComments(){
        var str = document.getElementById('code').innerHTML.replace(/(\/\*[\wа-я\'\s\r\n\*]*\*\/)|(\/\/[\wа-я\s\'\;]*)|(\<![\-\-\s\wа-я\>\/]*\>)/ig, "");
        document.getElementById('code').innerHTML = str;
    }
</script>
Shady Alset
  • 5,548
  • 4
  • 21
  • 34
  • Can you provide me full JS code? With testing of course, because it doesn't work for me – malcoauri May 05 '16 at 13:53
  • @malcoauri ok, i've updated [Jsfiddle](https://jsfiddle.net/Shady_Alset/ss6L9dwa/) and snippet on my answer – Shady Alset May 05 '16 at 14:42
  • @malcoauri Have you tried my last updated [fiddle](https://jsfiddle.net/Shady_Alset/xezeffge/1/) in previous comment ? is there any problem with it ? – Shady Alset May 06 '16 at 13:30
1
comment1 = ' I dont like oneline comment. to parsing. // like this comment.'
comment2 = ' also i hate multiple line comment
    /*
    like
    this.*/'

comment1.replace(/\s*(?:\/\/).*?$/gm , '')
// but you can't delete multiple line commet with regular grammar. like comment2

RegExp is base on regular grammar. it means regular grammar parser is a finate state machine and can't save state so regexp can't delete like multiple comment it can only oneline comment.

if you want to delete multiple line comment, then you have to write parser. or use something else not regexp.

JaeIL Ryu
  • 159
  • 10
1

i find this very useful and small solution

const word = ` 
      /**  @page type
      *       page    = ".page-body"
      *       popup   = ".pop-up-body"
      *       overlay = ".overlay-body" // new classes
      * 
      */
     
 
    return {
      "static" : '.page-body, .overlay-body, .pop-up-body, .card-wrapper { margin : 5px !important } .row { padding: 5px !important}'
    }
  `
console.log(word.replace(/\/*[^*]*.[^]*\//g,''))
rajratna maitry
  • 378
  • 3
  • 9