在javascript中替换字符串中的字母

时间:2015-03-15 12:21:02

标签: javascript regex

我试图用字符串中的相应字母替换下划线字符串中的下划线(请参阅代码段中的完整代码)到目前为止,我得到了一些奇怪的错误,它不会检查所有的强调还是会错过一个,无论如何要解决它?如果需要,我很乐意重建它。

    var underscore = "";
    var letter;;

    var wordList = ["apple", "peach", "pear", "mango", "banana", "paper", "pens", "laptop", "desk", "chair", "star", "sky", "moon", "sun", "planets"];

    var word = wordList[Math.floor(Math.random() * wordList.length)];

    for (i = 0; i < word.length; i++)   {
        var underscore = underscore + "_ ";
    }    

   var replaceletter = 0
                for (i = 0; i < word.length; i++)   {
                    replaceletter = word.indexOf(letter, replaceletter);
                    underscore = underscore.replace(underscore.charAt(replaceletter), word.charAt(replaceletter));
                }

&#13;
&#13;
/* Hangman Game CSS File */
body
{
	background-color: #1B264F;
}

#main {
	background-color: #5386E4;
	height: 97vh; 
   	width: 95vw;
   	vertical-align: middle;

}
canvas {
    padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
    margin-top: auto;
    margin-bottom: auto;
}
&#13;
<!DOCTYPE html>
<html>
	<head>
		<title>Hangman by Lachlan Teale</title>	
		<meta name="description" content="Lachlan Teale's Hangman Game 2015">
		<meta name="keywords" content="hangman, lachlan, teale, Javascript">
		<meta charset="UTF-8">
		<meta name="author" content="Lachlan Teale">
		<link rel="stylesheet" type="text/css" href="style.css">
	</head>
	<body>
	<canvas id="main" width="1920" height="1080" style="border:1px solid #d3d3d3;"></canvas>

	<script type="text/javascript">

	//setting variables
		var canvas = document.getElementById('main');
     	var context = canvas.getContext('2d');
      	var underscore = "";
      	var letter;
      	var complete = false;

	//list of words
		var wordList = ["apple", "peach", "pear", "mango", "banana", "paper", "pens", "laptop", "desk", "chair", "star", "sky", "moon", "sun", "planets"];

	//picking a random word from the list
		var word = wordList[Math.floor(Math.random() * wordList.length)];

	//print out the underscores for the number of letters
		for (i = 0; i < word.length; i++)	{
			var underscore = underscore + "_ ";
		}

		context.font = '50pt Calibri';
      	context.textAlign = 'center';
      	context.fillStyle = '#E2E2E3';
      	context.fillText(underscore, canvas.width * 0.5, canvas.height * 0.70);

    //correct letter text
      	context.font = 'bold 30pt Calibri';
      	context.textAlign = 'center';
      	context.fillStyle = '#E2E2E3';
      	context.text
      	context.fillText("Correct Letters", canvas.width * 0.08, canvas.height * 0.05);

    //Wrong Letter text
      	context.font = 'bold 30pt Calibri';
      	context.textAlign = 'center';
      	context.fillStyle = '#E2E2E3';
      	context.text
      	context.fillText("Wrong Letters", canvas.width - (canvas.width * 0.08), canvas.height * 0.05);

	//checking which button is pressed
		window.addEventListener('keydown', function(event) {
			if ( event.keyCode >= 65 && event.keyCode <= 90 ) {
    			context.clearRect(0, canvas.height * 0.80, canvas.width, canvas.height);  
        		letter = String.fromCharCode( event.keyCode ).toLowerCase();
        		context.font = '50pt Calibri';
      			context.textAlign = 'center';
      			context.fillStyle = '#E2E2E3';
      			context.fillText(letter, canvas.width * 0.5, canvas.height * 0.85);
      		}
		});

	//checking if back key is pressed
		document.addEventListener('keydown', function(event) {                     
    		if ( event.keyCode == 8 ) {											   
    			context.clearRect(0, canvas.height * 0.80, canvas.width, canvas.height); 
    		}
    	});

	//checking if enter is pressed
      	document.addEventListener('keydown', function(event) {                     
    		if( event.keyCode == 13 ) {
    //checking if letter is in the word
    			var replaceletter = 0
       			for (i = 0; i < word.length; i++)	{
    				replaceletter = word.indexOf(letter, replaceletter);
    				underscore = underscore.replace(underscore.charAt(replaceletter), word.charAt(replaceletter));
    			}

				context.clearRect(canvas.width * 0.4, canvas.height * 0.3, canvas.width *0.7, canvas.height * 70);
    			context.font = '50pt Calibri';
      			context.textAlign = 'center';
      			context.fillStyle = '#E2E2E3';
      			context.fillText(underscore, canvas.width * 0.5, canvas.height * 0.70);
			}
    	});
		
		</script>
	</body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您可以使用此循环替换它们:

for (i = 0; i < word.length; i++) {
    underscore = underscore.replace("_", word.charAt(i));
}

对此可能有更优雅的解决方案,但即使这是你想要的,我也不太明白。

答案 1 :(得分:-1)

这是我第一次在Stackoverflow中发帖。我一直在寻找你正在寻找的东西,但找不到任何东西。然后我解决了我自己的问题,并决定帮助其他人。

我创建了自己的功能,非常简单,我希望这会对你有所帮助。该函数包含3个参数:

参数1:您要取代的字母或字符
参数2:字符串本身
参数3:要替换的字母的索引。

这是功能:

function replaceAtIndex(character, word, index) {
    var tempStr = "";

    for (var n = 0; n < word.length; n++) {
        if (n == index) {
            tempStr += character;
        } else {
            tempStr += word[n];
        }
    }

    return tempStr;
}

它基本上做的是创建一个全新的字符串为空,并将原始字符串中的每个字母逐个添加到新的空字符串中,直到索引为止,然后添加要替换它的字符而是在那个指数,并恢复其余的。

所以你如何使用它是这样的:

var word= "abcdefg";
console.log(word); 
word = replaceAtIndex("z", word, 3);
console.log(word); 

结果:
ABCDEFG
abczefg

我希望这有帮助!