tags:

views:

137

answers:

6

Is there any way to access split values without putting them into separate value?

var content = "some|content|of"; 

var temp = content.split("|");   
var iwilluseit = "something" + temp[1] + temp[2]

How to do this w/o temp variable ?? (inline in setting of iwilluseit var)

+3  A: 

It's incredibly inefficient, but you could call split multiple times:

var iwilluseit = 'something' + content.split('|')[1] + content.split('|')[2];

There's also the slice() + join() option:

var iwilluseit = 'something' + content.split('|').slice(1,2).join('');

Really, though, just creating the temp variable is the best way to go.

Joel Coehoorn
A: 

No, you need to assign the result of Array.split() to an intermediate variable before it can be used, unless you don't mind the performance hit of calling Array.split() for each value you want to grab.

You could patch String.protoype to add a method that would take an array of strings and substitute it into a string.

Bryan Kyle
+1  A: 

content.split("|").slice(1,3).join("")

Georg Fritzsche
A: 

How about:

var iwilluseit = "something" + content.split("|").slice(1,3).join(""));
Phil Ross
A: 

You can also do:

var iwilluseit = "something" + content.substr( content.indexOf( "|" ) ).split("|").join("");

Of course, this will only work if you are simply trying to remove the first value.

More importantly: Why do you need it to be in line?

Christopher W. Allen-Poole
The reason was that I only needed just one value from original content. So i thought that creating new variable for this One part is not necessary.
Jirka Kopřiva
Your example uses two parts. Huge difference there.
Joel Coehoorn
A: 

If the purpose of not assigning it to a variable is to be able to do this in a context where you can only have one Javascript expression, you could also use a closure, and assign it to the variable in it:

(function() { var temp = content.split("|"); return "something" + temp[1] + temp[2]; })()

Which would be usable in an expression context, and not have the performance hit.

Sami