Reputation: 6986
I am wanting to mask some paragraph text out until it is hovered, so if I have a string like,
Hello World
I would want that to be, Hell* *****
how can I replace all characters with with a * after 4 characters/letters?
I know I can do all the string like this,
str.replace(/./g, '*')
but how can I limit it to after the first 4 letters?
Upvotes: 1
Views: 79
Reputation: 163467
Another option could be capturing the first 4 non whitespace chars using ^(\S{4})
in group 1 and use that in the replacement.
Other non whitespace chars will be matched using an alternation followed by a single non whitspace char |\S,
and those matches will be returned as *
^(\S{4})|\S
let str = "Hello World"
.replace(/^(\S{4})|\S/g, (_, g1) => g1 ? g1 : '*');
console.log(str);
Upvotes: 0
Reputation: 3
I can do this by Splitting String in Two Parts:
let text = 'Hello World';
let str1 = text.substring(0, 4);
let str2 = text.substring(4).replace(/\S/g, '*');
let updatedStr = str1.concat(str2);
console.log(updatedStr);
/*
Single Line
let updatedStr = text.substring(0, 4) + text.substring(4).replace(/\S/g, '*');
*/
Regex Info :
You can combine them in single line Code :
Upvotes: 0
Reputation: 896
var str = "Hello World"
var after4= str.substr(0,4)+str.substr(4).replace(/[^\s]/g, '*')
console.log(after4)
Upvotes: 2