Removing comments from array of string in JavaScript

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.

Problem Example

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,'
];

Solution

The function iterates through each string character by character. When it encounters a comment starter, it stops processing until a newline character is found:

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

const removeComments = (arr = [], starters = []) => {
   const res = [];
   for(let i = 0; i ') {
            flag = true
         }
         if (flag) str += x
      };
      res.push(str);
   }
   return res;
};

console.log(removeComments(arr, starters));
[ 'red, green', 'jasmine,' ]

How It Works

The algorithm uses a flag-based approach:

  • flag = true: Characters are added to the result string
  • flag = false: Characters are ignored (comment mode)
  • When a comment starter is found, trailing whitespace is removed and flag is set to false
  • When a newline character is encountered, flag is reset to true

Alternative Implementation

Here's a more functional approach using map and regular expressions:

const removeCommentsRegex = (arr, starters) => {
   const pattern = new RegExp(`[${starters.map(char => `\${char}`).join('')}].*`, 'g');
   return arr.map(str => str.replace(pattern, '').trim());
};

const arr2 = [
   'hello world !comment here',
   'another line #comment too'
];
const starters2 = ['!', '#'];

console.log(removeCommentsRegex(arr2, starters2));
[ 'hello world', 'another line' ]

Conclusion

Both approaches effectively remove comments from strings based on starter characters. The first method offers more control for complex scenarios, while the regex approach provides cleaner code for simple comment removal.

Updated on: 2026-03-15T23:19:00+05:30

408 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements