Strip Comments

题目

Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.

Example:

Given an input string of:

apples, pears # and bananas
grapes
bananas !apples
The output expected would be:

apples, pears
grapes
bananas
The code would be called like so:

1
2
var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
// result should == "apples, pears\ngrapes\nbananas"

分析

注意题目里的\n是换行符的意思!

答案

1
2
3
4
5
6
7
8
9
10
11
function solution(input, markers) {
var input_arr = input.split("\n");
for (var i in markers) {
for (var j in input_arr) {
if (input_arr[j].indexOf(markers[i]) > -1) {
input_arr[j] = input_arr[j].substring(0, input_arr[j].indexOf(markers[i])).trim();
}
}
}
return input_arr.join("\n");
};