Masking a string
20,157
Solution 1
You could replace each pattern part with the wanted data.
function format(value, pattern) {
var i = 0,
v = value.toString();
return pattern.replace(/#/g, _ => v[i++]);
}
console.log(format(123456789, '## ## ## ###'));
Solution 2
I needed one that masks any character with a "*", from the beginning or end of the string, so I wrote the following:
"use strict";
module.exports = {
/**
* @param {string} str
* @param {string} maskChar
* @param {number} unmaskedLength
* @param {boolean} [maskFromStart]
* @returns {string}
*/
mask(str, maskChar, unmaskedLength, maskFromStart = true) {
const maskStart = maskFromStart ? 0 : Math.max(0, unmaskedLength);
const maskEnd = maskFromStart ? Math.max(0, str.length - unmaskedLength) : str.length;
return str
.split("")
.map((char, index) => {
if (index >= maskStart && index < maskEnd) {
return maskChar;
}
else {
return char;
}
})
.join("");
},
};
Comments
-
Pedro Pam almost 2 years
I need to put a received string in this format:
"## ## ## ###"
in typescript/javascriptEg:
"12 34 56 789"
I know there's
string-mask
and some way via JQuery, is there a simplier way to do it?