1

I'm trying to create a simple function that takes a string and a delimiter and then splits the string into an array based on the delimiter value. I'm trying to write this function without using the split method in javascript. So say I have a sampleInput = '123$456$789' and a delimiter = '$' then the function stringDelimiter(sampleInput, delimiter) will return ['123', '456', '789'].

    var stringDelimiter = function (sampleInput, delimiter) {

        var stringArray = [];
        var garbageArray = [];
        var j = 0;


        for (var i = 0; i < sampleInput.length; i++) {

            if (sampleInput.charAt(i) == delimiter) {
                garbageArray = sampleInput.charAt(i);
                j++;
            } else {
            if (!stringArray[j]) stringArray[j] = '';
            stringArray[j] += sampleInput.charAt(i);
            }
        }
        return stringArray;
    }

The problem I'm having is if the delimiter appears at the beginning of the string it returns the first element of the array undefined. I'm stuck as to how I can handle this case. So if I have sampleInput = '$123$456$789' and delimiter = '$' it returns ['123', '456', '789'] and not ['undefined','123', '456', '789']. Any help would be appreciated.

8
  • 3
    1) Why? 2) regular expressions Commented Jul 15, 2014 at 18:40
  • Generally, if there's a built-in function you can use, you may as well use it. Since split() is pretty well supported everywhere, I see few reasons you shouldn't use it. Commented Jul 15, 2014 at 18:40
  • 1
    This is probably for a school assignment where reinventing the wheel is common. Commented Jul 15, 2014 at 18:42
  • 1
    FWIW, the behaviour of the real split function would be to return an empty string in the first element of the result, not an undefined value. Commented Jul 15, 2014 at 18:43
  • Also, consider using indexOf() to directly find the index of the next delimiter, and substr to extract from the current position to there. Commented Jul 15, 2014 at 18:45

6 Answers 6

5

This is a little simpler, and it might do what you want:

var stringDelimiter = function (sampleInput, delimiter) {
    var stringArray = [''];
    var j = 0;

    for (var i = 0; i < sampleInput.length; i++) {
        if (sampleInput.charAt(i) == delimiter) {
            j++;
            stringArray.push('');
        } else {
            stringArray[j] += sampleInput.charAt(i);
        }
    }
    return stringArray;
}

Your garbageArray seemed unnecessary.

Sign up to request clarification or add additional context in comments.

Comments

1

What about using regular expressions?

function x_split(s)
{
     return s.match(/([^$]+)/g);
}

E.g. http://jsfiddle.net/2F9MX/2/

5 Comments

The title includes "without using the split method". I don't know why this is a requirement, possibly homework, but it's part of the specification here.
How is using match using the split method?
Total misread. I apologize. I saw the split in the function name and read it as part of the body. Sorry.
There are two flaws I see: First, the OP wanted the delimiter to be a parameter. Second, this has the same problem that it doesn't match the String.prototype.split behavior when the delimiter comes first (or last either.)
Check the fiddle, it does what s/he says it should do, that "$123$456$789" should return ['123', '456', '789'] and not ['undefined','123', '456', '789']. Adding the delimiter as a second parameter is left as an exercise for the reader ;-).
0

If the current character is delimiter and if the current iteration is 0, continue

Comments

0

This function accepts a string, a delimiter and a flag if empty (aka undefined, null or empty string) elements should be removed from the result array. (Not tested, it was a quick code for now.)

UPDATE

Now it's tested (a bit) and corrected, and I've created a jsFiddle here. Besides, it supports empty delimiter, empty input string, and delimiter with length > 1.

function CustomSplit(str, delimiter, removeEmptyItems) {
  if (!delimiter || delimiter.length === 0) return [str];
  if (!str || str.length === 0) return [];
  var result = [];
  var j = 0;
  var lastStart = 0;
  for (var i=0;i<=str.length;) {
    if (i == str.length || str.substr(i,delimiter.length) == delimiter)
    {
      if (!removeEmptyItems || lastStart != i)
      {
          result[j++] = str.substr(lastStart, i-lastStart);
      }
      lastStart = i+delimiter.length;
      i += delimiter.length;    
    } else i++;
  }
  return result;
}

3 Comments

fail's the OP's requirement not to use split itself.
!delimiter || delimiter.length === 0 is redundant. !"" is true
@megawac You're right, but those lines are just coming for me by instincts, rather longer check than forgotten check. (I used to do a similar check for expected arrays as well, and there it's not redundant if you want to include empty arrays in the condition.)
0

In case someone needs one for TypeScript (and MicroBit for which I wrote it), here's a altered version of @Scott Sauyet answer for TypeScript:

The code:

function splitString(sampleInput: string, delimiter: string): string[] {
    let stringArray = ['']
    let j = 0

    for (let i = 0; i < sampleInput.length; i++) {
        if (sampleInput.charAt(i) == delimiter) {
            j++;
            stringArray.push('')
        } else {
            stringArray[j] += sampleInput.charAt(i)
        }
    }
    return stringArray
}

Usage example

let myString = "Lorem ipsum dolor sit amet"
let myArray = splitString(myString, " ")
myArray[0]  // "Lorem"
myArray[1]  // "ipsum"

3 Comments

splitString('hello world','hello') fails
It's because delimiter is supposed to be a single character, not a word.
would be nice to support any number of chars.
0

You can use this method

const splitCode = (strValue, space) => {
let outPutArray = [];
let temp = '';
for(let i= 0; i< strValue.length; i++){
  let temp2 = '';
  for(let j= i; j<space.length+i;j++){
    temp2 = temp2+strValue[j];
  }
 if(temp2 === space){
    outPutArray.push(temp);
    i=i+space.length-1;
    temp = '';
  }else{
     temp = temp+strValue[i];
 }
}
return outPutArray.concat(temp)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.