Udders
Udders

Reputation: 6986

Replace characters in string with *, but only characters not spaces JavaScript regex

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

Answers (3)

The fourth bird
The fourth bird

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

Regex demo

let str = "Hello World"
  .replace(/^(\S{4})|\S/g, (_, g1) => g1 ? g1 : '*');
console.log(str);

Upvotes: 0

Well_Wisher13
Well_Wisher13

Reputation: 3

I can do this by Splitting String in Two Parts:

  1. First Part which would remain as it is.
  2. Second Part : I would replace all the Characters by required Character.
  3. Concat both the Strings

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 :

  • \S : Any other Character other then Space (Capital 'S')

You can combine them in single line Code :

Upvotes: 0

Yerrapotu ManojKiran
Yerrapotu ManojKiran

Reputation: 896

var str = "Hello World"    
var after4= str.substr(0,4)+str.substr(4).replace(/[^\s]/g, '*')

console.log(after4)

Upvotes: 2

Related Questions