在JavaScript中,如何用一个字符替换字符串中的所有字母

In JavaScript, how can I replace all the letters of a string with a single character?

本文关键字:字符串 替换 字符 JavaScript 何用一      更新时间:2023-09-26

我想做的是例如:

var variable = "Hello"

成为

*****

即用星号替换每个字母。请用JS。

通过数组对输入的长度重复*

> var variable = "Hello"
> Array(variable.length + 1).join("*");
> "*****"

试试这个可能会对你有所帮助。。

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>

这个答案可能很有帮助。

您可以用一个新的字符串更新字符串,该字符串的字符数与初始字符串相同:

var str = "Hello World!";
var my_char = "*";
str = Array(str.length+1).join(my_char);

向ES5添加一个ES6答案:

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

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