How to 'subtract' one string from another?
javascript, language-agnostic
Solution
You could split the value string and filter the characters which are unequal to the character at the same position of the mask string.
Then join the array for a new string.
function subtract(value, mask) {
return value.split('').filter(function (a, i) {
return a !== mask[i];
}).join('');
}
console.log(subtract("1-000-111", " - -"));
console.log(subtract("foo1-000-111", "foo - -"));
Problem
Suppose I have the following two strings: ``` var value = "1-000-111"; var mask = " - -"; ``` I want to subtract the `mask` from the `value`. In other words I want something like this: ``` var output = subtract(value, mask); // output should be 1000111 ``` What is the best way to implement `subtract()`? I have written this, but that doesn't seem elegant to me. ``` function subtract(value, mask) { while (mask.indexOf('-') >= 0) { var idx = mask.indexOf('-'); value = value.substr(0, idx) + value.substr(idx + 1); mask = mask.substr(0, idx) + mask.substr(idx + 1); } return value; } ``` Does JavaScript have something built-in to accomplish this? Note that, the masking characters are not limited to `-` (dash), but can be other characters as well, like `+`. But in a given case, the masking character can only be either `-` or `+`, which can therefore be sent to the `subtract()` function, which makes handling different masking character trivial. Also, the masking characters will be in arbitrary positions. Any language-agnostic answers are also welcome.