admin管理员组

文章数量:1323737

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.

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.

Share Improve this question asked Jul 15, 2014 at 18:38 user3743066user3743066 111 gold badge1 silver badge2 bronze badges 8
  • 3 1) Why? 2) regular expressions – Diodeus - James MacFarlane 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. – ArtOfCode Commented Jul 15, 2014 at 18:40
  • 1 This is probably for a school assignment where reinventing the wheel is mon. – Zach M. 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. – Alnitak 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. – Alnitak Commented Jul 15, 2014 at 18:45
 |  Show 3 more ments

6 Answers 6

Reset to default 4

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.

What about using regular expressions?

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

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

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

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;
}

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"

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)
}

本文标签: Writing a string splitting function without using the split method in javascriptStack Overflow