How can I find all of the spaces in a sentence and replace ignore them?
我正在做一个JavaScriptHangman游戏,我需要打印出与随机选择的单词长度相同的破折号。我做到了,但它也打印出了一个破折号,以填补句子中的空白,所以我怎么能忽略这些空格,只打印出一个破折号,以填补句子中的字母呢?感谢您的帮助。
这是打印破折号的代码
1 2 3 4 | for(var i = 0; i < sayings[randomSaying].length; i++) { progress.innerHTML +="-"; } |
随机变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var sayings = [ "cash on the nail", "charley horse", "foul play", "bury the hatchet", "hands down", "if the cap fits", "mumbo jumbo", "see red", "stone the crows", "thick and thin", ] sayings.toString(); var randomSaying = Math.floor(Math.random()*sayings.length); |
不需要忽略空格,只需替换字母即可。
1 | progress.innerHTML = sayings[randomSaying].replace(/[a-z]+/g,"-"); |
一行代码,全部在一行中,比循环更有效;)
不能肯定,但我想你应该看看这个:
1 2 3 4 5 6 7 | function randomSaying(sayingsArray){ var p = sayingsArray[Math.floor(Math.random()*(sayingsArray.length+1))]; var d = p.replace(/\s/g, '').replace(/./g, '‐'); return {phrase:p, dashes:d}; } var obj = randomSaying(sayings); // obj.phrase is phrase obj.dashes is dashes |
在您的
1 2 3 4 5 6 7 8 | var hiddenSaying =""; for(var i = 0; i < sayings[randomSaying].length; i++) { if (sayings[randomSaying].charAt(i) === ' ') hiddenSaying +=""; else hiddenSaying +="-"; } progress.innerHTML = hiddenSaying; |