- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Removing comments from array of string in JavaScript
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 −
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 === '
') { 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,' ]
- Related Articles
- Removing Negatives from Array in JavaScript
- Removing duplicate objects from array in JavaScript
- Removing first k characters from string in JavaScript
- Removing adjacent duplicates from a string in JavaScript
- Removing punctuations from a string using JavaScript
- Removing an element from an Array in Javascript
- Removing duplicates from a sorted array of literals in JavaScript
- Removing redundant elements from array altogether - JavaScript
- JavaScript Algorithm - Removing Negatives from the Array
- Removing a specific substring from a string in JavaScript
- Removing all spaces from a string using JavaScript
- Completely removing duplicate items from an array in JavaScript
- Removing all the empty indices from array in JavaScript
- Removing an element from the end of the array in Javascript
- Removing an element from the start of the array in javascript

Advertisements