2019-03-13 Daily Challenge
What I've done today is Strip Comments in JavaScript.
Regex is awesome!
CodeWars
Problem
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:
var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
// result should == "apples, pears\ngrapes\nbananas"
Solution
const escape = (string) => string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
function solution(input, markers) {
if (input[input.length-1] !== "\n") input += "\n";
markers.map(m => escape(m)).forEach(m => input = input.replace(RegExp(`\ *${m}.*?\n`), "\n"));
return input.slice(0,-1);
};
////
function solution(input, markers){
return input.replace(RegExp("\\s?[" + markers.join("") + "].*(\\n)?", "gi"), "$1");
}
////
function solution(input, markers) {
return input.split('\n').map(
line => markers.reduce(
(line, marker) => line.split(marker)[0].trim(), line
)
).join('\n')
}