I have a phone number and I want to display it like censored form. For example I have: +923451234567
I want to display it like: +923*******67
Str.replace function will be used, but how:
var str = '+923451234567'
str.replace(i_Dont_Know_What, '*');
So in this case string contains 13 characters. And I want to replace 5th-11th character with " * "
I have found this somewhere, but this is not what I want.
var str = "name(replace these parenthesis by @)domain.com";
var patt1 = /\(.*@\)/i;
document.write(str.replace(patt1,"@"));
How would I achieve this?
Nice and simple one line replace with a substring match, no need for a messy regex here.
var str = '+923451234567';
console.log(str.replace(str.substring(4,11), "*******"));
Multple ways of doing it, one way is a simple reg expression
console.log("+923451234567".replace(/(\+\d{3})\d{7}/,"$1*******"))
regex to keep 3 num characters at the beginning and 2 at the end
regex explanation: https://regex101.com/r/xR6pRD/1
var str = '+923451234567'
str = str.replace(/(\+?\d{3})(\d+)(\d{2})/g, function(match, start, middle, end) {
return start + "*".repeat(middle.length) + end;
});
document.write(str);
You could use a dynamic approach by giving the length and take an offset for shifting the replacement charcters.
function replaceMiddle(string, n) {
var rest = string.length - n;
return string.slice(0, Math.ceil(rest / 2) + 1) + '*'.repeat(n) + string.slice(-Math.floor(rest / 2) + 1);
};
console.log(replaceMiddle('+923451234567', 7));
console.log(replaceMiddle('+923451234567', 6));
console.log(replaceMiddle('+923451234567', 5));
console.log(replaceMiddle('+923451234567', 4));
console.log(replaceMiddle('+923451234567', 3));
console.log(replaceMiddle('+923451234567', 2));
console.log(replaceMiddle('+923451234567', 1));
.as-console-wrapper { max-height: 100% !important; top: 0; }
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