Skip to content

Instantly share code, notes, and snippets.

@ThadeusAjayi
Created May 28, 2017 23:35
Show Gist options
  • Save ThadeusAjayi/1b87f9ed52822081cd199b952ce8ca29 to your computer and use it in GitHub Desktop.
Save ThadeusAjayi/1b87f9ed52822081cd199b952ce8ca29 to your computer and use it in GitHub Desktop.
Alternative function to str.split() in javascript where you have have the error "TypeError: sentence.split is not a function"
function split(sentence){
var arrayPosition = 0;
var oneWord = "";
var newSentence = sentence + " ";
var split = new Array();
for(var j = 0; j < newSentence.length; j++){
if(newSentence[j] === " "){
split.push(oneWord);
arrayPosition++;
oneWord = "";
}else{
if(!isNaN(newSentence[j])){
//don't add to the string
}else{
oneWord += newSentence[j];
}
}
}
return split;
}
@natanaeldeveloper
Copy link

natanaeldeveloper commented Feb 27, 2023

function split(str, pattern){
    
    let arr = []
    let index = 0
    
    do {
        index = str.search(pattern)
        if(index != 0 && index != -1) {
            arr.push(str.slice(0, index))
        }
        str = str.slice(index + 1)
    } while(index != -1)
    
    if(str.length > 0) {
        arr.push(str)
    }
    
    return arr
}

console.log(split(' Texto Texto Texto Texto ', ' '))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment