删除两个字符串中不存在的字符



我有两个字符串,一个是可以更改的掩码,另一个是用户输入。

我需要保留掩码格式并删除两个字符串中不存在的数字

rawValue: "25155122"
value: "2 5155 1220 0000" 
例如,我有这两个字符串,预期的结果将是:
newValue = "2 5155 122" <= 
the zeros are removed as they are a mask and user has not typed in the rest of the numbers yet

这是我到目前为止所尝试的:

const strSet = str => new Set(str.split(''));
const setDiff = (a, b) => new Set(Array.from(a).filter(item => !b.has(item)));
const prune = (str, set) => str.split('').filter(x => set.has(x))
.join('');

const diff = setDiff(strSet(rawValue), strSet(value));
const a1 = prune(value, diff);
const b1 = prune(rawValue, diff);

谢谢你的帮助

不确定您到底想要什么,但希望这能解决您的问题…

const rawValue = "25155122"
const value = "2 5155 1220 0000" 
//convert string value of rawValue into an array
const rawValueArray = rawValue.split("");
//converts string value of Value into an array
const valArray = value.split("");
//filters out array value in VALUE that's not included in RAWVALUE
const newArray = valArray.filter(val => rawValueArray.includes(val));
console.log("new_value_without_spaces", newArray.join(""))
//filters out array value in VALUE that's not included in RAWVALUE and also ignores the spaces
const newArrayWithSpaces = valArray.filter(val => val === " " || rawValueArray.includes(val));
console.log("new_value_with_spaces", newArrayWithSpaces.join(""))

最新更新