settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Print all the symbols of a string - each on a new line

+2 votes

Write a JavaScript function that prints all the symbols of a string, each on a new line. The input comes as a single string argument.

Examples:

Input:

'Hello, World!'

Output:

str[0] -> H
str[1] -> e
str[2] -> l
str[3] -> l
str[4] -> o
str[5] -> ,
str[6] -> 
str[7] -> W
str[8] -> o
str[9] -> r
str[10] -> l
str[11] -> d
str[12] -> !

The output is printed on the console, each letter on a new line.

asked in JavaScript category by user paulcabalit
edited by user golearnweb

2 Answers

+1 vote

Here is the function:

function printStr(strInput) {
    for (let i = 0; i < strInput.length; i++) {
        console.log(`str[${i}] -> ${strInput[i]}`);
    }
}

printStr("Hello, World!");

 

answered by user matthew44
0 votes

Another solution with for in:

function print(str) {
    for (let i in str) {
        console.log(`str[${i}] -> ${str[i]}`);
    }
}

print("Hello, World!");

 

answered by user golearnweb
function pl(input) {
    let string = String(input);
    for (let i = 0; i < string.length; i++) {
        console.log("str[" + i + "] -> " + string[i]);
    }
}
...