Reputation: 92547
I have email and want to replace each character between first letter and @ to *. Example:
[email protected] -> j*********@gmail.com
Here is my code, but it produce one star instead of many - I stuck on it:
let h="[email protected]".replace(/(.)(.*)@/,'$1*')
console.log(h);
Any solutions?
Upvotes: 3
Views: 259
Reputation: 283
A global flag is what you are missing in your Regex.
I got this oneshot Regex that does the job:
"[email protected]".replace(/(?!^)(?=.+@)./g,'*')
let h = "[email protected]".replace(/(?!^)(?=.+@)./g,'*');
console.log(h);
Upvotes: 3
Reputation: 627083
A simple regex replacement will do:
let h="[email protected]".replace(/(?!^).(?=.*@)/g, '*')
console.log(h);
Details
(?!^)
- not the start of the string.
- any char but a line break char(?=.*@)
- immediately to the right, there must be 0+ chars other than line break chars and then a @
.See the online regex demo.
Upvotes: 1
Reputation: 7675
You can pass a replacement function in String.prototype.replace, e.g:
const result = '[email protected]'.replace(
/^(.)(.*)(@.+)$/,
(match, ...groups) => groups[0] + '*'.repeat(groups[1].length) + groups[2]
);
console.log(result);
Upvotes: 2
Reputation: 666
Your regex will match the whole part and replace that with a star. Instead you want the regex to be able to match every char that you want to match separately. This will work:
let h="[email protected]".replace(/(?<=^.+)(?<!@.*)[^@]/g,'*')
console.log(h);
To break the regex down:
(?<=^.+)
will match the start of the string, the first character and any number of characters after it using a positive lookbehind. That concept will work to match the string but not be included in the resulting match.
(?<!@.*)
is a negative lookbehind to make sure we don't match anything after the @ symbol.
[^@]
matches any character that is not @.
g
at the end means global, that makes it match any number of times instead of only once.
Upvotes: 2
Reputation: 1110
Just writing:
let e = Array.from("[email protected]").reduce((arr, char, index) => arr.concat(arr.includes('@') || char === '@' ? char : index === 0 ? char : '*'), []).join('');
console.log(e)
Upvotes: 2
Reputation: 350760
You could use the callback argument of replace
:
let h = "[email protected]".replace(/(.)(.*)@/, (_, first, rest) =>
first + "*".repeat(rest.length) + "@"
);
console.log(h);
Upvotes: 5