evilReiko
evilReiko

Reputation: 20473

split string into array then get element in 1 line

I usually do this:

var str = "hello_blue_world";
var arr = str.split("_");
var target = arr[1];

But since I don't need the arr, I noticed that I can do this:

var str = "hello_blue_world";
var target = str.split("_")[1];

My question:

  1. Is this approach supported in different ECMAScript versions?
  2. Is it safe to do this approach?

Upvotes: 1

Views: 402

Answers (2)

Mike
Mike

Reputation: 1175

Yes to both. It's safe and supported.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4.14

Returns an Array object into which substrings of the result of converting this object to a String have been stored

If this is true your str.split("_") evaluates to array and you should be able to use [x] to get any of the returned elements.

Upvotes: 3

spassvogel
spassvogel

Reputation: 3541

Perfectly safe and supported on Chrome, Firefox (Gecko), Internet Explorer, Opera and Safari

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

Upvotes: 1

Related Questions