0

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;
 }
1
  • 1
    cadena.match(/\S+/g); Commented Mar 1, 2015 at 19:49

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.