如何找到句子中的所有空格并替换忽略它们?

时间:2016-05-19 00:42:24

标签: javascript html string

我正在开发一个JavaScript Hangman游戏,我需要打印出与随机选择的单词长度相同的破折号。我已经完成了这个,但它也打印出了句子中的间隙,所以如何忽略这些空格,只打印出句子中的字母?任何帮助表示感谢。

这是打印破折号的代码

for(var i = 0; i < sayings[randomSaying].length; i++)
{
   progress.innerHTML += "-";
}

随机变量

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);

3 个答案:

答案 0 :(得分:2)

您不需要忽略这些空格,只需替换字母

即可
progress.innerHTML = sayings[randomSaying].replace(/[a-z]+/g, "-");

单行代码,全部在一行中,比循环更有效;)

答案 1 :(得分:1)

if循环中使用for语句。另外,不要使用innerHTML +=,因为它会导致浏览器不得不一遍又一遍地重新解析DOM。这样做:

var hiddenSaying = "";
for(var i = 0; i < sayings[randomSaying].length; i++) {
    if (sayings[randomSaying].charAt(i) === ' ')
        hiddenSaying += " ";
    else
        hiddenSaying += "-";
}
progress.innerHTML = hiddenSaying;

答案 2 :(得分:1)

不能肯定地说,但我认为你应该看看这个:

function randomSaying(sayingsArray){
  var p = sayingsArray[Math.floor(Math.random()*(sayingsArray.length+1))];
  var d = p.replace(/\s/g, '').replace(/./g, '&#8208;');
  return {phrase:p, dashes:d};
}
var obj = randomSaying(sayings);
// obj.phrase is phrase obj.dashes is dashes