Removing comments from array of string in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in array of strings, arr, as the first argument and an array of special characters, starters, as the second argument.

The starter array contains characters that can start a comment. Our function should iterate through the array arr and remove all the comments contained in the strings.

For example, if the input to the function is:

const arr = [
   'red, green !blue',
   'jasmine, #pink, cyan'
];
const starters = ['!', '#'];

Then the output should be −

const output= [
   'red, green',
   'jasmine,'
];

Example

Following is the code −

 Live Demo

const arr = [
   'red, green !blue',
   'jasmine, #pink, cyan'
];
const starters = ['!', '#'];
const removeComments = (arr = [], starters = []) => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      let str = ''
      let flag = true
      for (let x of arr[i]) {
         if (starters.includes(x)) {
            flag = false
            str = str.replace(/\s+$/, '')
         } else if (x === '\n') {
            flag = true
         }
         if (flag) str += x
      };
      res.push(str);
   }
   return res;
};
console.log(removeComments(arr, starters));

Output

Following is the console output −

[ 'red, green', 'jasmine,' ]
raja
Published on 21-Apr-2021 16:45:16
Advertisements