1

I need a function that works like split

var string = "a|b|c" console.log(string.split('|'))

to get a string and split it using loop

function splitstr(str, charToSplit){

      }

I want the output of ('a|b|c', '|') to be ["a", "b", "c"]

Aniket G
  • 3,471
  • 1
  • 13
  • 39
Ar3f
  • 25
  • 6
  • 1
    Possible duplicate of [How do I split a string, breaking at a particular character?](https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character) – DevJem Mar 27 '19 at 00:42
  • 2
    @DevJem this question is not related to that proposed dupe question. – Ele Mar 27 '19 at 00:44
  • What have you tried so far? –  Mar 27 '19 at 00:49

2 Answers2

3

Here is a slightly simpler solution that works correctly:

function splitStr(str, separator) {
  const parts = [];
  let nextPart = '';
  for (let i = 0; i <= str.length; i++) {
    if (str[i] === separator || i === str.length) {
      parts[parts.length] = nextPart;
      nextPart = '';
    } else {
      nextPart += str[i]
    }
  }
  return parts;
}

console.log(splitStr("abc|abcd|ac", "|"));
Aniket G
  • 3,471
  • 1
  • 13
  • 39
Stefan Blamberg
  • 816
  • 9
  • 24
1

You can use the code below.

This code had 8 steps to it.

  1. Loops through the string
  2. Checks if the current item is equal to charToSplit
  3. If it is, it loops through the values in between startIndex and your current index (excluding your current index, which is the character you want to split on)
  4. It first sets the value of output[currentIndex] to an empty string (since using += on something that doesn't exist doesn't work correctly
  5. Then it adds the current letter you are on to output
  6. startIndex is set to your current index + 1 (which is the character after the character that you want to split on)
  7. currentIndex is increased by 1 since you're now on the next set of values
  8. Finally, the code returns output

Note: The final extra loop after the first loop is there to add the last value to your output array.

function splitstr(str, charToSplit) {
  var output = [];
  var currentIndex = 0;
  var startIndex = 0;

  for (var i = 0; i < str.length; i++) {
    if (str[i] == charToSplit) {
      output[currentIndex] = "";
      for (var x = startIndex; x < i; x++) {
        output[currentIndex] += str[x];
      }
      startIndex = i + 1;
      currentIndex++;
    }
  }
  output[currentIndex] = "";
  for (var i = startIndex; i < str.length; i++) {
    output[currentIndex] += str[i];
  }

  return output;
}

console.log(splitstr("abc|abcd|ac", "|"));
Aniket G
  • 3,471
  • 1
  • 13
  • 39