如何在不使用javascript中的split函数的情况下将字符串拆分为单词。我想知道一点帮助。 这是我的代码:
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;
}
答案 0 :(得分:1)
我不明白你的变量名是什么意思,所以我无法修复代码。这是另一个:
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)
答案 1 :(得分:0)
假设您也无法使用@Oriol建议的内容,我会使用递归函数,如下例所示:
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;
}
}
用法:
_split(' one two three ');
//=> ["one", "two", "three"]