'how to replace all in a given string except the last 4 digits like **** **** **** 4587 [duplicate]
"\\d(?=\\d{4})","*"
I've tried it like that but it does not seem to be working it gives me the exact same string i entered to the scanner
Solution 1:[1]
Maybe match
on a simple regex to get each group of numbers, then map
over that array to produce the desired result, joining
it up into a new string at the end.
const str = '1234 1234 1234 5678';
const re = /(\d+)/g;
const out = str
.match(re)
.map((el, i, arr) => {
if (i < arr.length - 1) return '****';
return el;
})
.join(' ');
console.log(out);
Solution 2:[2]
You can simply slice the string and save its four-last characters and append it to the result string after your done with the replacement
let str = '6135 4639 4990 1032'
function hideChars(str) {
const stars = str.slice(0, str.length - 4).replace(/\d/g, "*")
const fourLast = str.slice(str.length - 4, str.length)
return stars + fourLast
}
const result = hideChars(str)
// result = **** **** **** 1032
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Andy |
Solution 2 |