替换字符串中的值

时间:2018-11-07 21:29:56

标签: javascript string function loops methods

请问我是否已经问过这个问题;我已经在网站上搜索了这个问题,但还没有发现。

我正在创建一个猜词游戏,但我的最后一个功能遇到了麻烦。函数参数是用户输入的字符(“字符”),随机生成的单词(“ word”)和该单词的加扰版本(“ scrmbldword”)。例如,单词可能是“ chilly”,并且加扰的版本将带有相应数量的下划线“ ______”。此功能的作用是接受用户输入,扫描该字母的“单词”,如果在单词中找到该字母,则用相应的字母替换“ scrmbldword”的下划线。

例如,单词将是“ chilly”,而用户输入将是字符“ l”;我需要scrmbldword成为“ ___ ll _”。

function unscrambledWord(character, scrmbldword, word) {
  for (k = 0; k < word.length; k++) {
    if (character == word[k]) {
      var tempLetter = word[k];
      console.log(tempLetter)
      tempWord = scrmbldword.replace(scrmbldword[k], character);
      console.log(tempWord);
    }
  }
}

谢谢所有答案,但是当我将它们复制并粘贴到我的代码中时,它们将无法工作。我试图理解各种答案背后的代码,以便我自己编辑它们,但是在大多数情况下我不理解。如果我提供更多背景信息,它可能会对您有所帮助,所以这完全是我的文件...

<!DOCTYPE html>
<html lang="en-us">

<head>
  <meta charset="UTF-8">
  <title>Word Guess Game</title>
</head>

<body>

  <div>
    <p id="directions-text">Type any letter to start playing</p>
    <p id="userchoice-text"></p>
    <p id="userguesslist-text"></p>
    <p id="unscrambledword-text"></p>
  </div>

  <script type="text/javascript">
    var userGuesses = [];
    var unknownWord = "";

function wordGenerator() {
  var computerChoices = ["lowly", "start", "chilly", "bun", "bead", "friend", "return", "view", "cloth", "frogs", "celery", "basin", "stand", "special", "broad", "abaft", "plead", "quartz", "mark", "tempt", "shop", "stone", "scorch", "taboo", "hoax", "spiffy", "insure"];
  var cpuWord = computerChoices[Math.floor(Math.random() * computerChoices.length)];
  console.log(cpuWord);
  return cpuWord;
};
var computerWord = wordGenerator();

function scrambledWord(string) {
  var knownWord = ""
  if (string.length == 3) {
    knownWord = "___"
  } else if (string.length == 4) {
    knownWord = "____"
  } else if (string.length == 5) {
    knownWord = "_____"
  } else if (string.length == 6) {
    knownWord = "______"
  } else if (string.length == 7) {
    knownWord = "_______"
  }
  return knownWord;
}
var unknownWord = scrambledWord(computerWord);

var directionsText = document.getElementById("directions-text");
var userChoiceText = document.getElementById("userchoice-text");
var userGuessList = document.getElementById("userguesslist-text");
var unscrambledWordText = document.getElementById("unscrambledword-text");

document.onkeyup = function (event) {

  var userGuess = event.key;

  if ((userGuess === "a") || (userGuess === "b") || (userGuess === "c") || (userGuess === "d") || (userGuess === "e") || (userGuess === "f") || (userGuess === "g") || (userGuess === "h") || (userGuess === "i") || (userGuess === "j") || (userGuess === "k") || (userGuess === "l") || (userGuess === "m") || (userGuess === "n") || (userGuess === "o") || (userGuess === "p") || (userGuess === "q") || (userGuess === "r") || (userGuess === "s") || (userGuess === "t") || (userGuess === "u") || (userGuess === "v") || (userGuess === "w") || (userGuess === "x") || (userGuess === "y") || (userGuess === "z")) {
    userGuesses.push(userGuess);
    directionsText.textContent = "";

    userChoiceText.textContent = "You chose: " + userGuess;
    userGuessList.textContent = "You have guessed: " + userGuesses;
    unscrambledWordText.textContent = "The word is: " + unknownWord;
    wordChecker(userGuess)
  } else {
    alert("You did not enter an alphabetical character.")
  }
};

function wordChecker(input) {
  if (computerWord.includes(input)) {
    alert("You guessed a correct character")
    unscrambledWord(input, unknownWord, computerWord)
  } else {
    alert("You guessed an incorrect character")
  }
}

function unscrambledWord(character, scrmbldword, word) {
  for (k = 0; k < word.length; k++) {
    if (character == word[k]) {
      var tempLetter = word[k];
      console.log(tempLetter)
      tempWord = scrmbldword.replace(scrmbldword[k], character);
      console.log(tempWord);
    }
  }
}

3 个答案:

答案 0 :(得分:4)

根据我的理解,您可以尝试

function unscrambledWord(character, word, scrmbldword = "_".repeat(word.length)) {
	return [...scrmbldword].map((d, i) => d == '_' && word[i] == character ? character : d).join('')
}

console.log(unscrambledWord('l', 'chilly'))

答案 1 :(得分:1)

我认为Nitish Narang确实是一个不错的答案,但是如果您真的想使用现有功能,则可以尝试定义和使用replaceAt函数,如下所示:

function unscrambledWord(character, scrmbldword, word) {
  for (k = 0; k < word.length; k++) {
    if (character == word[k]) {
      var tempLetter = word[k];
      console.log(tempLetter)
      tempWord = scrmbldword.replaceAt(k, character);
      console.log(tempWord);
    }
  }
}

String.prototype.replaceAt=function(index, replacement) {
    return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}

unscrambledWord("l", "______", "chilly")

答案 2 :(得分:1)

您可以使用带有全局标记的RegExp来使用replace方法,该标记告诉我们替换该RegExp的所有实例。

RegExp(`[^${character}]`, "g")

我们正在制作一个正则表达式,该正则表达式可以匹配除提供的字符以外的任何字符。

function unscrambledWord(character, word) {
    const notCharacter = RegExp(`[^${character}]`, "g")
    return word.replace(notCharacter, "_")
}