
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Strings 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,' ]
Advertisements