Reputation: 301
How can I split string into words without using split function in javascript. I wonder for a little help. this is my code:
function trocearCadena(cadena) {
var posEspacios = buscarEspacios(cadena);
var palabras = [];
var j = 0;
while (true) {
var pos = posEspacios.shift();
var subcad = (j == 0) ? cadena.substring(0, pos) : cadena.substring(j + 1, pos);
palabras.push(subcad);
j += pos;
if (j > cadena.length) {
var ultpal = cadena.substring(pos + 1);
palabras.push(ultpal);
break;
}
}
return palabras;
}
function buscarEspacios(cadena) {
var espacios = [];
var pos = -1;
do{
pos = cadena.indexOf(" ", ++pos);
if (pos != -1) espacios.push(pos);
} while (pos != -1);
return espacios;
}
Upvotes: 0
Views: 1415
Reputation: 2662
Assuming that you also can't use what @Oriol suggested, I would use a recursive function like in the following example:
function _split(s, arr) {
var
str = s.trim(),
words = arr || [],
i = str.indexOf(' ');
if(i !== -1) {
words.push(str.substr(0, i)); // collect the next word
return _split(str.slice(i + 1), words); // recur with new string and words array to keep collecting
} else {
words.push(str); // collect the last word
return words;
}
}
Usage:
_split(' one two three ');
//=> ["one", "two", "three"]
Upvotes: 0
Reputation: 214949
I don't understand what your variable names mean, so I wasn't able to fix the code. Here's another one:
str = "How can I split string into words without using split function in javascript."
var words = [""];
for(var i = 0; i < str.length; i++)
if(str[i] !== " ")
words[words.length - 1] += str[i];
else if(words[words.length - 1])
words.push("");
document.write(words)
Upvotes: 1