Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing middle n characters in JavaScript

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?

like image 657
Noman Ali Avatar asked Oct 26 '17 14:10

Noman Ali


4 Answers

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), "*******"));
like image 123
Mark Walters Avatar answered Oct 23 '22 09:10

Mark Walters


Multple ways of doing it, one way is a simple reg expression

console.log("+923451234567".replace(/(\+\d{3})\d{7}/,"$1*******"))
like image 7
epascarello Avatar answered Oct 23 '22 09:10

epascarello


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);
like image 6
Apolo Avatar answered Oct 23 '22 07:10

Apolo


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; }
like image 2
Nina Scholz Avatar answered Oct 23 '22 09:10

Nina Scholz