I have a string like this that is split up:
var tokens = "first>second>third>last".split(">");
What I would like in each iteration is for it to return
Iteration 0: "last"
Iteration 1: "third>last"
Iteration 2: "second>third>last"
Iteration 3: "first>second>third>last"
I am thinking of using decrementing index for loop.... but is there a more efficient approach ?
for (int w = tokens.length-1; w == 0; w--)
{
}
asked Jan 17, 2011 at 3:31
KJW
15.3k51 gold badges144 silver badges249 bronze badges
5 Answers 5
var tokens = "first>second>third>last".split(">");
var out = []
while(tokens.length) {
out.unshift(tokens.pop());
console.log(out.join('>'))
}
answered Jan 17, 2011 at 3:41
mikerobi
21k5 gold badges49 silver badges43 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
fmark
-1. This stack based approach is neat but incorrect. It reverses the order of the tokens, which the OP did not ask for. Use of the
unshift() method of the array type should do what you want, but may not work in some versions of Internet Explorer.mikerobi
@fmark, thanks, I didn't read carefully enough, but it was pretty simple to fix.
fmark
@mikerobi Sorry to be a pedant, but your fixed version is still incorrect. Now it produces output from the wrong "end" of the token list. You should be reversing the
out variable prior to printing it, not the input tokens.mikerobi
@fmark, thats what I get for posting code without testing it, but I finally corrected it. Funny thing is, my wrong answer was accepted.
KJW
@mikerobi, an accepted answer is a great incentive to get people fix it too.
OTOH this is the simplest aproach
var tokens = "first>second>third>last".split(">");
text = ''
for (w = tokens.length-1; w >= 0; w--)
{
if(text != ''){
text = tokens[w] + '>'+text;
}else{
text = tokens[w]
}
console.log(text);
}
1 Comment
fmark
You could avoid the use of an if statement by using the
join() method.You could try the following:
var tokens = "first>second>third>last".split(">");
for (var w = 0; w < tokens.length; w++)
{
var substr = tokens.slice(tokens.length - 1 - w, tokens.length).join(">");
console.log("Iteration " + w + ": " + substr)
}
answered Jan 17, 2011 at 3:47
fmark
58.9k27 gold badges104 silver badges107 bronze badges
Comments
You could also use join to reverse the original split. I'm not sure about efficiency but it's quite legible:
var tokens = 'first>second>third>last'.split('>');
for (var i = tokens.length - 1; i >= 0; --i) {
var subset = tokens.slice(i).join('>');
console.log(subset);
}
answered Jan 17, 2011 at 3:51
Romain
2,3481 gold badge24 silver badges31 bronze badges
Comments
var tokens = "first>second>third>last".split(">");
var text = [];
for (var i = tokens.length; --i >= 0;) {
text.unshift(tokens[i]);
var str = text.join(">");
alert(str); // replace this with whatever you want to do with str
}
Should do the trick.
answered Jan 17, 2011 at 3:43
Peter C
6,2971 gold badge28 silver badges38 bronze badges
Comments
lang-js