I need to put a received string in this format:
"## ## ## ###"
in typescript/javascript
Eg:
"12 34 56 789"
I know there's string-mask
and some way via JQuery, is there a simplier way to do it?
The mask may be alphabetic, numeric or contain blank characters or any of the special characters valid within a string name. For an inclusive mask the string is accepted for further processing; for an exclusive mask the string is rejected.
Data masking is a method of creating a structurally similar version of an organization´s data that can be used for purposes such as software testing and user training. The purpose of data masking is to protect the actual data while having a functional substitute when the real data is not required.
Protective masks are pieces of kit or equipment worn on the head and face to afford protection to the wearer, and today usually have these functions: Providing a supply of air or filtering the outside air (respirators and dust masks).
You could replace each pattern part with the wanted data.
function format(value, pattern) {
let i = 0;
const v = value.toString();
return pattern.replace(/#/g, _ => v[i++]);
}
console.log(format(123456789, '## ## ## ###'));
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("");
},
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With