Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92547

Replace each captured char to *?

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

Answers (6)

Samir
Samir

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,'*')
  • Negative look ahead to exclude the first char.
  • Positive look ahead for all chars preceding the @ char.
  • Global flag to replace all captures.

let h = "[email protected]".replace(/(?!^)(?=.+@)./g,'*');

console.log(h);

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

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

antonku
antonku

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

Bob
Bob

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

alejoko
alejoko

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

trincot
trincot

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

Related Questions