Blog
In JavaScript Write a Function to Split a String without using split();
Posted on June 5, 2015 in Algorithms, JavaScript by Matt Jennings
/* Function to Split a String into an Array using a single space as a
delimiter without using the split(); function
*/
function mySplit(str, delim) {
var tokens = [];
var token = "";
for(var n = 0; n < str.length; n++) {
if(str[n] != delim) {
token += str[n];
}
else {
tokens.push(token);
token = "";
}
}
if(token.length > 0) {
tokens.push(token);
}
return tokens;
}
console.log(mySplit("hello world and stuff", " "));
Leave a Reply