简体   繁体   English

如何从另一个字符串中“减去”一个字符串?

[英]How to 'subtract' one string from another?

Suppose I have the following two strings: 假设我有以下两个字符串:

var value = "1-000-111";
var mask = " -   -";

I want to subtract the mask from the value . 我想从value 减去 mask 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() ? 实现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? JavaScript是否有内置功能来完成此任务? 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. 但是在给定的情况下,屏蔽字符只能是-+ ,因此可以发送到subtract()函数,这使得处理不同的屏蔽字符变得微不足道。 Also, the masking characters will be in arbitrary positions. 此外,屏蔽字符将处于任意位置。

Any language-agnostic answers are also welcome. 任何与语言无关的答案也是受欢迎的。

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 - -")); 

Just iterate through value and check if the corresponding value in mask is not - 只需迭代值并检查mask的相应值是否为-

  var value = '1-000-111'; var mask = ' - -'; var result = ''; for (var i = 0; i < value.length; i += 1) { if (mask[i] !== '-') { result += value[i]; } } console.log(result); 

Mask can be any characters if you iterate through each character of value and compare to same position in mask: 如果遍历每个值的字符并与掩码中的相同位置进行比较,则掩码可以是任何字符:

Example using Array#reduce() on split() value 在split()值上使用Array#reduce()的示例

 var value = "1-000-111"; var mask = " - -"; var unmasked = value.split('').reduce((a,c,i) => (mask[i] === c) ? a : a+c); console.log(unmasked ) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM