Split array in JS

Viewed 119

I am making a Pure js hangman game. I have an array with different words. I have tried to split the array into single letters, but I am getting "," for every letter.

e.g: in array [station], when I split it returns "s,t,a,t,i,o,n".

so i want to split it with out the ",".

here is the code:

// Word we want to use to the hangman game
let words = ["definition", "programming", "relation", "station","gamification","playstation"];

//This chooses random word from words array and * with words length to not go over the array length
let random = Math.floor(Math.random(words) * words.length);

//This will split up the word ex: station to [s,t,a,t,i,o,n]
let wordSplit = words[random].split('');


let wordLetters = document.getElementById("letters")

wordLetters.innerHTML = wordSplit;

function wordInput(){
    let lettersDiv = document.getElementById("letters");
       let html = "<p id = 'letters'>" + wordSplit + "</p>";
       return html;
}

how it displays

5 Answers

You can try replace

let wordSplit = words[random].split('');

with

let wordSplit = words[random].split('').join(" ");  // there is a space in join 
let wordSplit = words[random].split('');

This will assign wordSplit to ["d", "e", "f", "i", "n", "i", "t", "i", "o", "n"] which is an array without the ,.

However the problem arises when you do this:

wordLetters.innerHTML = wordSplit;

Just a little background, the HTML DOM doesn't understand any datatype other than string (No int, arrays etc.). So when you do the above command, the DOM Renderer can't set the innerHTML to be a variable of datatype Array, so what it does instead is call the toString() method on it.

so the above command basically becomes (internally):

wordLetters.innerHTML = wordSplit.toString()

The toString() on lists gives us a comma-separated string, which is what you see.

So the problems isn't in the split part but the design of the page, you'll have to run some sort of .map to assign each character to another div, or something like that.

Or just do: wordLetters.innerHTML = wordSplit.join(' ')

This should replace the , with a

I'm not quite sure if I understood the problem, but .join("") should to the trick:

let html = "<p id = 'letters'>" + wordSplit.join("") + "</p>";

i don't know whether this is correct or not, but i think using .join("") can solve it.

let wordSplit = words[random].split('').join(" ")

use spacing into split method.

example:

let wordSplit = words[random].split(' ').join('')
Related