1

So, as a relatively new programmer, I'm trying to create a very simple ASCII hangman game. I'm trying to figure out how to create a string of underscore's(_) based on the length of the word chosen.

For example, take the word Kaiser, I'd like to take, 'word.length(where word = "Kaiser")and convert it to "_ _ _ _ _ _`". Thanks in advance!

user5680735
  • 703
  • 2
  • 7
  • 21
  • It's as easy as `var u = new Array("Kaiser".length).join('_')`, and based on that answer, this looks a lot like a duplicate of [**Repeat Character N Times**](http://stackoverflow.com/questions/1877475/repeat-character-n-times) – adeneo Dec 13 '15 at 23:38

3 Answers3

6

My first guess is something like this would work.

var underscored = string.split('').map(function(char) {
  return char = '_ ';
}).join('');

Get every character in the string with the split function, and change the state of every character, using the map function. However, this will just give us an array. We need to perform type conversion again to turn it back to a string. To do this, we can use the join method. The delimiter we join is simply an empty string ''.

Another possibility is with the replace function

var underscored = string.replace(/./g, '_ ');

The regular expression here is very simple. The period . indicates any character. The global(g) flag means find all instances of the previous regex.

The second parameter of this function is what we want these characters to become. Since we want a space between underscores, this will be _.

Note that the replace method is not destructive. In other words, it does not modify the original array. You would need to store this in a separate variable. Because if you call string again, kaiser will be returned.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
3
var str = "Kaiser";
var resStr = "";
for (i = 0; i < str.length; i++) {
    resStr = resStr + " _";
}
Med Abida
  • 1,214
  • 11
  • 31
1

You don't have to replace anything just create new string based on length of the first word, example :

var underscore_word = Array(word.length).join("_ ");

Take a look at Repeat Character N Times.

Hope this helps.

Community
  • 1
  • 1
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101