Writing a string splitting function without using the split method in javascript

javascript split string at index
javascript split string by comma
javascript split regex
split array javascript
string to array javascript
split string without using split function javascript
string split() method
split join javascript

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.

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.

JavaScript String split() Method, The split() method is used to split a string into an array of substrings, and returns the new array. Note: The split() method does not change the original string. Specifies the character, or the regular expression, to use for splitting the string. Example. Use a letter as a separator: var str = "How are you doing today?"; JavaScript String Split Example Using Split() Method November 24, 2019 JsTutorials Team javascript In this tutorial, I am going to explain How To Split String in JavaScript .The JavaScript have a split() method to break the string into the array.We will create different scenario to split string into array using JavaScript.

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

Find the Longest Word in a String (without using the split method , I'm wondering how to solve this without using the str.split method. so far I have pushed the string into an array but I have no way of splitting off each individual function findLongestWordLength(str) { let words = [] words.push(str); https://​learn.freecodecamp.org/javascript-algorithms-and-data-structures  The split() method is used to split a string into an array of substrings, and returns the new array. Tip: If an empty string ("") is used as the separator, the string is split between each character. Note: The split() method does not change the original string.

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

String.prototype.split(), The split() method divides a String into an ordered set of substrings, puts these If separator is omitted or does not occur in str , the returned array at the beginning (or end) of the string, it still has the effect of splitting. The following example defines a function that splits a string into an array of strings  The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one .

What about using regular expressions?

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

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

JavaScript, The same also happens when the separator is not present in the string. In this example the function split() creates an array of strings by splitting str Why split the <script> tag when writing it within document.write() method in JavaScript ? I can't use the split method for strings so I'm a bit stuck. I was prompted to declare a new string array with more entries than I will actually need, storing new words as I encounter space characters in this new array. Then, at the end, create a new String array with just enough entries, and copy over the non-null elements of the first array over.

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"

JavaScript String Split Example Using Split() Method, The JavaScript have a split() method to break the string into the array. The split​() method returns an array of strings, that is formed after splitting a The method are using regex to split string. function getRGB(hexVal) split string without any separator,The source string will return as its original string. In JavaScript, split() is a string method that is used to split a string into an array of strings using a specified delimiter. Because the split() method is a method of the String object, it must be invoked through a particular instance of the String class.

How can I split a String without using the Split method? : javahelp, For example, the input "the quick brown fox jumped over the lazy dog" will be translated I can't use the split method for strings so I'm a bit stuck. You can pass the tokenizer a delimiter(a separating character or string which indicates around basic CRUD functions or it may be because I do not know the search keyword. str.split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument. The syntax of the function is as follows: str.split(separator, limit) Arguments The first argument to this function is a string which specifies the points where the split has to take

Index, Slice, Split, and Manipulate JavaScript Strings, Each character in a JavaScript string can be accessed by an index number, and all in a string gives us a number of ways to work with and manipulate strings. Note that 11 is ? , but ? is not part of the returned output. slice() will return We will use the split() method to separate the array by a whitespace  The Headlines hide 1. The split method in JavaScript 2. An example of split string with dot (.) operator 3. An example of split without a separator 4. A demo to use the limit parameter in JavaScript split string method 5. Splitting a phone number with hyphen as separator demo 6. A demo of split …

Split() method to create array by breaking string using delimiterin in , Creating array by breaking strings using delimiters in split function. and create an array out this by using one space as delimiter in a split() method. var str="​this is my new tutorial"; var a1 = new Array(); a1=str.split(" "); document.write(a1.​join(" <br> ")); Breaking without any delimiter <script type="text/javascript"> This method splits a String object into an array of strings by separating the string into substrings. The split method returns the new array. Also, when the string is empty, split returns an array containing one empty string, rather than an empty array

Comments
  • 1) Why? 2) regular expressions
  • 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.
  • This is probably for a school assignment where reinventing the wheel is common.
  • 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.
  • Also, consider using indexOf() to directly find the index of the next delimiter, and substr to extract from the current position to there.
  • 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.)
  • 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 ;-).