How to "subtract" one line from another?
Suppose I have the following two lines:
var value = "1-000-111";
var mask = " - -";
I want to subtract mask
from value
. In other words, I want something like this:
var output = subtract(value, mask);
// output should be 1000111
What's the best way to implement it subtract()
? I wrote this, but it 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;
}
Is there something built-in in JavaScript to accomplish this? Note that escape characters are not limited to -
(dash), but can be other characters, for example +
. But in this case, the escape character can be either -
or +
, which can therefore be sent to a function subtract()
, making it trivial to handle another escape character. In addition, masking characters will be in arbitrary positions.
Any language agnostic answers are also appreciated.
source to share
You can split the string of values ββand filter for characters that are not equal to a character at the same place in the mask string.
Then join the array to a new line.
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 - -"));
source to share
The mask can be any character as long as you iterate over each character of the value and compare it to the same position in the mask:
Array # reduce () example for split () value
var value = "1-000-111";
var mask = " - -";
var unmasked = value.split('').reduce((a,c,i) => (mask[i] === c) ? a : a+c);
console.log(unmasked )
source to share