1

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--)
{

}

5 Answers 5

3
var tokens = "first>second>third>last".split(">");

var out = []

while(tokens.length) {
   out.unshift(tokens.pop());
   console.log(out.join('>'))
}
Sign up to request clarification or add additional context in comments.

5 Comments

-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.
@fmark, thanks, I didn't read carefully enough, but it was pretty simple to fix.
@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.
@fmark, thats what I get for posting code without testing it, but I finally corrected it. Funny thing is, my wrong answer was accepted.
@mikerobi, an accepted answer is a great incentive to get people fix it too.
0

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

You could avoid the use of an if statement by using the join() method.
0

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)
}

Comments

0

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);
}

Comments

-1
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.

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.