3gwebtrain
3gwebtrain

Reputation: 15299

How to replace a string according to their length with "*" (astrik) letter

From the back-end json data, i am receiving a "password" infromation. But I requested to hide the password information in the html page.

I know there is a way to hide using the input type "password". But in this html just i am showing the details hiding the password.

I am trying to replace the string using the regexp method. but not working.

here is my try:

var st = "Shchool"; //it is 7 letters, i need to print 7 '*'

st.replace(/./g, "*"); // i am trying to replace.

console.log(st);

Upvotes: 0

Views: 103

Answers (1)

Frogmouth
Frogmouth

Reputation: 1818

The method String.replace() return a new string with the replacing text, and it doesn't modify the string where you apply the method.

var st = "Shchool";
st.replace(/./g, "*"); // returns new string "*******"

You need to assign the result to the variable, if you want to change it:

st = st.replace(/./g, "*"); // assign the replaced string back to st

Now you can log the string:

console.log(st);

MDN - String.replace() returns a new string

Consider masking password with * in back-end, replacing it in front-end isn't a good idea!


Test code

var st = "Shchool"; // It has 7 letters, I need to print 7 '*'

st.replace(/./g, "*"); // The variable st is NOT modified

console.log("LOG1:",st);

st = st.replace(/./g, "*"); // Assign the return value to st

console.log("LOG2",st);

// Look at the console

Upvotes: 5

Related Questions