如何替换字符串中的重复字符 - Javascript

时间:2016-08-15 08:42:14

标签: javascript string

这里有一个基本的刽子手游戏。似乎工作正常,但我无法获得重复的字符猜测才能正常工作。现在银行里只有两个字,"爆米花"和"苹果"。你第一次猜到" p"对于苹果,它填写第一个p,但不会填写第二个。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hangman!</title>
</head>
<body>
<h1>Hangman</h1>
<h2>Press a letter to guess.</h2>
<div id="secret"> </div>

<script>
var computerChoices = ['apples', 'popcorn'];
var progress = "";
// This chooses a word from the set randomly.

    var secretWord = computerChoices[Math.floor(Math.random() * computerChoices.length)];
    for (i=0; i < secretWord.length; i++){
        progress += "_";
    }
// When the user presses the key it records the keypress and then sets it to userguess
    document.onkeyup = function(event) {
    var letter = String.fromCharCode(event.keyCode).toLowerCase();


    if (secretWord.indexOf(letter) > -1){
        console.log("Good Guess!");
        index = secretWord.indexOf(letter);
        progress = progress.substr(0, index) + letter + progress.substr(index + 1);

        // Placing the html into the secret ID
        document.querySelector('#secret').innerHTML = progress;

            if ((/([a-zA-Z]).*?\1/).test(secretWord)) {             
                console.log("Yep, there's a duplicate here")
     }}else{
        console.log ("Eeeeeennnnnghh! Wrong! Try again dumbassss!");
    }



}
</script>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

尝试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hangman!</title>
</head>
<body>
<h1>Hangman</h1>
<h2>Press a letter to guess.</h2>
<div id="secret"> </div>

<script>
var computerChoices = ['apples', 'popcorn'];
var progress = "";
// This chooses a word from the set randomly.

    var secretWord = computerChoices[Math.floor(Math.random() * computerChoices.length)];
    for (i=0; i < secretWord.length; i++){
        progress += "_";
    }
// When the user presses the key it records the keypress and then sets it to userguess
    document.onkeyup = function(event) {
    var letter = String.fromCharCode(event.keyCode).toLowerCase();


    if (secretWord.indexOf(letter) > -1){
        console.log("Good Guess!");
        index = secretWord.indexOf(letter);
        progress = progress.substr(0, index) + letter + progress.substr(index + 1);
        secretWord = secretWord.substr(0, index) + '*' + secretWord.substr(index + 1);
        console.log('Secret Word is: ' + secretWord);

        // Placing the html into the secret ID
        document.querySelector('#secret').innerHTML = progress;

            if ((/([a-zA-Z]).*?\1/).test(secretWord)) {             
                console.log("Yep, there's a duplicate here")
     }}else{
        console.log ("Eeeeeennnnnghh! Wrong! Try again dumbassss!");
    }



}
</script>
</body>
</html>

答案 1 :(得分:1)

您必须使用第二个参数在循环中调用indexOf。 示例:

$("#register-form").submit(function(e) {
    e.preventDefault();
    if ($("fname").val().trim() == "" || $("lname").val().trim() == "") {
        $("div#ack").html("Please enter both your first name and your surname");
    } else {
        $.post(this.action, $(this).find(':input').serializeArray(), function(data) {
            $("div#ack").html(data);   
        });   
    }     
});

你再次执行此操作,但是给出了&#34;结果&#34;第二个参数中的变量:

var word = "popcorn";
var result = word.indexOf("p");
console.log(result); // Shows "0"

你可以做一个while循环逻辑:

var previousResult = 0;
var word = "popcorn";
// Give as second argument the previous result increased by 1
var result = word.indexOf("p", previousResult + 1); 
console.log(result); // Shows "2"

答案 2 :(得分:1)

您当前的代码正在寻找第一个匹配的字母。不管怎样,你需要一个循环来处理重复的字符。

但是我建议另一个修改:你应该维护到目前为止已经尝试过的所有字母(好的或坏的)列表,而不是跟踪'进度掩码'。

secretWordprogress没有提供足够的信息来检测已经尝试过的错误信件 - 这可能是您最终希望实施的功能。另一方面,您可以使用progress和已尝试过的字母列表,在每次需要时快速重建secretWord

假设已尝试的字母存储在letters字符串中。然后可以使用显式循环计算progress,例如:

// classic for loop
for(i = 0, progress = ''; i < secretWord.length; i++) {
  progress += letters.indexOf(secretWord[i]) == -1 ? '_' : secretWord[i]
}

或隐式循环,例如:

// functional programming
progress = secretWord.split('').map(function(letter) {
  return letters.indexOf(letter) == -1 ? '_' : letter;
}).join('');

或:

// regular expression: replace() with custom callback
progress = secretWord.replace(/./g, function(letter) {
  return letters.indexOf(letter) == -1 ? '_' : letter;
});

或:

// regular expression: replace() without callback
progress = secretWord.replace(new RegExp('[^' + letters + ']', 'g'), '_');

下面是一些示例代码,显示了使用此方法的游戏逻辑。

var secretWord = 'apple',
    letters    = '';

function play(letter) {
  if(letters.indexOf(letter) != -1) {
    console.log("You've already tried '" + letter + "' ...");
  }
  else {
    letters += letter;

    if(secretWord.indexOf(letter) == -1) {
      console.log(letter + ' -> wrong!');
    }
    else {
      var progress = secretWord.replace(new RegExp('[^' + letters + ']', 'g'), '_');

      console.log(letter + ' -> ' + progress);
      
      if(progress == secretWord) {
        console.log('Well done!');
      }
    }
  }
}

play('i');
play('e');
play('p');
play('e');
play('a');
play('l');