Separates letters by javascript line

Asked

Viewed 174 times

-4

I am new to programming and would like someone to help me, please. I need to sort the letters one word per line

var n=require("readline-sync")

var b1
var b2

b2=n.question("Digite uma palavra")

b1=b2.split("")
console.log(b1)

Basically my code is like this, but I need each letter of the word to be on a different line, someone can help me?

3 answers

6

Remember that your string has characters whose code-point is higher than U+FFFF, the behavior may not be as expected, see:

const string = 'Olá! ';

string
  .split('')
  .forEach((char) => console.log(char));

Learn more about why in this answer.

So, if you want to split strings that can contain these types of characters correctly, you can use more modern language features such as scattering operator (...):

const string = 'Olá! ';

[...string].forEach((char) => console.log(char));

Or you can use a loop for..of, using the iteration protocol built-in of strings, as well as the scattering notation above, in a more explicit way:

const string = 'Olá! ';

for (const char of string) {
  console.log(char);
}

3

Just add the special character to the string \n in each character. Use the method split to separate and then use the method join to combine everything with this character.

This way, each letter of the string will be printed in different lines.

let palavra = "PROGRAMAÇÃO";
palavra = palavra.split("").join("\n");

console.log(palavra);

Another even simpler way if you need to keep the characters separate is to use the method forEach passing a function that receives an item from the list and prints.

let palavra = "PROGRAMAÇÃO";
palavra = palavra.split("");

palavra.forEach((caractere) => {
    console.log(caractere);
});

0

You can make a forEach in your array, would look like this:

b1.forEach(letter => console.log(letter))
  • It is not necessary to use the \n in this case because the console.log already makes line break at the end.

  • Really not necessary, thanks for the tip

Browser other questions tagged

You are not signed in. Login or sign up in order to post.