每次刷新字符串中的页面时,我都想要随机多个下划线...
<html>
<body>
<p id="demo"></p>
<p id="temo"></p>
<p id="jemo"></p>
<p id="remo"></p>
<script>
var i;
var x="Sachin Tendulkar";//String in which i want underscores
var res=x.split("");
for(i=1;i<=7;i++)//here in this for loop i generated random numbers and accessing the elements at that indexes and try to put underscores there.
{
var j = document.getElementById("demo").innerHTML=Math.floor(Math.random()* ((x.length-1)/2));
var t = res[j];
var f = document.getElementById("jemo").innerHTML=x.replace(res[j],"_");
var l = document.getElementById("jemo").innerHTML=f.replace(res[j],"_");
}
</script>
</body>
</html>
答案 0 :(得分:0)
您可以使用.slice()
,.concat()
代替.replace()
。
var x = "Sachin Tendulkar";
for (var i = 1, y = x; i < 7; i++) {
// alternatively `Math.floor(Math.random() * x.length)`
var n = Math.floor(Math.random() * ((x.length - 1) / 2));
y = y.slice(0, n).concat("_", y.slice(n + 1))
}
console.log(y);