malcoauri
malcoauri

Reputation: 12189

Remove comments from string with JavaScript using JavaScript

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.

Upvotes: 14

Views: 23037

Answers (6)

AymKdn
AymKdn

Reputation: 3907

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)

Upvotes: 27

rajratna maitry
rajratna maitry

Reputation: 508

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,''))

Upvotes: 1

JaeIL Ryu
JaeIL Ryu

Reputation: 189

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.

Upvotes: 1

Abdullah
Abdullah

Reputation: 998

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, '/')

);

Upvotes: 5

Shady Alset
Shady Alset

Reputation: 5714

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>

Upvotes: 1

MarcoS
MarcoS

Reputation: 17711

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

Upvotes: 6

Related Questions