settingsAccountsettings
Menusettings

Q: Split a String with a Delimiter in JavaScript

+2 votes

Write a javascript function that splits a string with a given delimiter.

The input comes as 2 string arguments. The first one is the string you need to split and the second one is the delimiter.

Examples:

Input:
One-Two-Three-Four-Five
-

Output:
One
Two
Three
Four
Five

The output should consist of all elements you’ve received, after you’ve split the given string by the given delimiter. Each element should be printed on a new line.

asked in JavaScript category by user golearnweb

2 Answers

+2 votes

The solution:

function splitDel(input, delimiter) {
    console.log(input.split(delimiter)
        .join("\n"));
}

splitDel("One-Two-Three-Four-Five", "-");

 

answered by user ak47seo
0 votes

My JavaScript code:

function main(string, del) {
    let splittedEl = string.split(del);

    for (let i = 0; i < splittedEl.length; i++) {
        console.log(splittedEl[i]);
    }

    ////or:
    //
    //for (let i in splittedEl) {
    //   console.log(splittedEl[i]);
    //}
    //
    ////or:
    //
    //for (let i of splittedEl) {
    //    console.log(i);
    //}

}

main("One-Two-Three-Four-Five", "-");
  • This “main” function will hold all of the code of our solution.
  • Now that we have the string and the delimiter, we can split the string and save the split elements we received as result to the action we did.
  • The split() function returns an array of elements, which we can iterate over. The last thing we need to do is print each of the elements on a new line.
answered by user andrew
...