.replace总是把角色放在第一个位置

时间:2015-03-16 09:20:17

标签: javascript regex

我正在尝试创建一个刽子手游戏。当字母与变量“word”中的字母匹配时,我需要用变量“letter”中的字母替换变量“underscore”中的下划线。这样做的任何方式?

for( i = 0; i < word.length; i++ ) {
    if (word[i] === letter) {
        underscore = underscore.replace(underscore.charAt(i*2), letter);
    }
}

上面是我的代码的特定部分,我现在试图替换它,但它只会在信件/开头之后替换下一个下划线,无论我做什么。如果您需要有关其工作原理的更多详细信息,请参阅下面的完整代码。

提前致谢。

/* 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;
}
<!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
    			alert(word);
    								
				for( i = 0; i < word.length; i++ ) {
					if (word[i] === letter) { 
					   	underscore = underscore.replace(underscore.charAt(i*2), letter);
					}
				}

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

      			alert(underscore); 
			}
    	}); 

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

1 个答案:

答案 0 :(得分:0)

由于字符串underscore中的所有字符均为“_”,因此当您运行underscore.replace(underscore.charAt(i*2), letter);时 它查看i*2处字符的字符串,然后用letter替换该字符的第一个实例(您可以在此处找到此文档:http://www.w3schools.com/jsref/jsref_replace.asp)。

您可能想要做的是定义如下函数:

function replaceAt(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}

并使用该函数代替replace()

您可以声明该功能,然后在之前调用.replace()之前调用它。当您调用它时,只需将str替换为字符串(underscore),将index替换为您想要新字母的索引,将ltr替换为您想要的新字母(letter)。