skip to Main Content

I’ve been trying to run the following code but all I get is Error: str.stringSplit is not a function

const str = '7The quick 8brown jhbjhb 78646845fox jum56ps.';

function stringSplit(str, delimiter) {
   var substrings = [];

   if (delimiter === '') {
      for (var i = 0; i < str.length; i++) {
         substrings.push(str[i]);
      }
      return substrings;
   }
}

console.log(str.stringSplit(7));

2

Answers


  1. this way to call your function:

    console.log(stringSplit(str,7));
    

    or you can create a prototype in this way:

    String.prototype.stringSplit = function(delimiter) {
      var substrings = [];
    
       if (delimiter === '') {
          for (var i = 0; i < this.length; i++) {
             substrings.push(this[i]);
          }
       }
       return substrings;
    };
    const str = '7The quick 8brown jhbjhb 78646845fox jum56ps.';
    console.log(str.stringSplit(7));
    
    Login or Signup to reply.
  2. From what I can read from your post is a misunderstanding of how JavaScript works. From what you’re trying to achieve I think there is already a built in method from JavaScript CORE such as split from the String prototype.

    By using this syntax after calling a function:

    str.stringSplit(7) // You are actually calling a function that should exist on the Prototype of the String primitive
    

    It’s very important to know what you want to obtain… Do you want to split the string using a separator ? Do you want to learn how the prototype works ? Usually altering the prototype with methods like this it’s not best practice since it can name collide with other existing functions and before creating one check the MDN docs if maybe there isn’t an existing method that achieve’s what you want.

    The verified answer provides an valid example of how to add a method to the String prototype and if you want to call your function simply use this syntax (the name of the function followed by curly braces and add in the braces the params you’d like to use)

    stringSplit(stringFoo, numberHere)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search