-2

What I want to do is for example:

var variable = "Hello"

becomes

*****

i.e each letter replaced with an asterisk. In JS please.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
swisstony
  • 1,667
  • 3
  • 18
  • 27
  • You probably spent more time writing this question than it would've taken you to lookup an existing question. See [this](https://stackoverflow.com/search?q=[javascript]+replace+all+characters+of+a+string). – tne Mar 19 '15 at 11:49
  • possible duplicate of [Fastest method to replace all instances of a character in a string](http://stackoverflow.com/questions/2116558/fastest-method-to-replace-all-instances-of-a-character-in-a-string) – tne Mar 19 '15 at 11:50

4 Answers4

0

Repeat * for the length of the input by way of an array

> var variable = "Hello"
> Array(variable.length + 1).join("*");
> "*****"
Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

Try this may help you..

function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace(/[^abc]/g, "*");
    document.getElementById("demo").innerHTML = res;
}
<!DOCTYPE html>
<html>
<body>

<p>Click the button to replace "Hello" with "*****" </p>

<p id="demo">Hello</p>

<button onclick="myFunction()">Try it</button>
  </body>
</html>
coDe murDerer
  • 1,858
  • 4
  • 20
  • 28
0

This answer can be helpful.

You can update the string with a new one that has as many characters as the initial string:

var str = "Hello World!";
var my_char = "*";
str = Array(str.length+1).join(my_char);
Community
  • 1
  • 1
koukouviou
  • 820
  • 13
  • 23
0

Adding a ES6 answer, to the ES5 one:

var foo = "Hello"; 
var bar  = "*".repeat(foo.length);

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

ZER0
  • 24,846
  • 5
  • 51
  • 54