Nidhin N
Nidhin N

Reputation: 53

replace space in javascript

I need to replace all the letters in a sentence to * (asterisks).

My code is

var password='hello world';
password.replace(/\S/g, '*');

All the letters are getting replaced but not the space. How can that too be replaced ?

Upvotes: 3

Views: 719

Answers (3)

Scott
Scott

Reputation: 3765

Change your code to:

var password='hello world';
password=password.replace(/[\S ]/g, '*');

Tested and illustrated here: http://jsfiddle.net/HSP2P/

Upvotes: 0

Ally
Ally

Reputation: 4942

What about

password.replace(/[a-zA-Z|\s]/g, '*');

This matches letters and spaces but use the other answer if you ment all characters. Although even better use an input of type "password" if that will achieve what you want to do.

Upvotes: 1

Chris Van Opstal
Chris Van Opstal

Reputation: 37537

\s will match spaces

\S (capital S) will match everything BUT spaces

. will match every character

So to replace every character:

password.replace(/./g, '*');

Upvotes: 5

Related Questions