user13299875
user13299875

Reputation: 21

Regex : select the x first AND the x last letters to replace them

I am trying to select the five first and five last characters to replace them, let's say like for "[email protected]" to become "*****fgh@abcdefg*****" The regex i am using doesn't work properly but I can't understand the reason why. Thanks a lot !

const strRe = str => str.replace(/(^.{5})(.{5}$)/gi, '*****');

Upvotes: 0

Views: 44

Answers (2)

Dario
Dario

Reputation: 6280

Does it need to be a regex? You can just slice your string:

const strRe = str => `*****${str.slice(5, -5)}*****`

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163277

Your pattern (^.{5})(.{5}$) does not match, as it should match exactly 10 characters.

You could use an alternation | instead to match either 5 chars at the start or 5 char at the end of the string. Note that for the replacement you don't need the capturing groups.

str.replace(/^.{5}|.{5}$/

let s = "[email protected]";
const strRe = str => str.replace(/^.{5}|.{5}$/gi, '*****');
console.log(strRe(s));

Upvotes: 1

Related Questions