0

I currently have this in my code:

var user = this.value.split("@")[0];
var domain = this.value.split("@")[1];

I would love to be able to do something like this:

var user, domain = this.value.split("@");

(But of course this creates an empty variable "user", and assigns "domain" to the array returned by .split())


I managed to do this in PHP like so:

list($user, $domain) = explode('@', $_POST['user']);

Was wondering if there is a JavaScript equivalent?

TRGWII
  • 648
  • 5
  • 14

1 Answers1

2

ES6 will add destructuring assignments, which lets you do very nearly what you've written:

// Will be valid in ES6
var [user, domain] = this.value.split("@");

...but you can't do it (in most engines) today. Instead, you need an intermediate variable:

var parts = this.value.split("@");
var user = parts[0];
var domain = parts[1];

...or just duplicate the split as you've done.

Here's a live example that works in recent versions of Firefox, which already have destructuring assignments:

// Requires that destructuring assignments work on your browser;
// recent Firefox has them
var value = "coolness@example.com";
var [user, domain] = value.split("@");
snippet.log("user = " + user);
snippet.log("domain = " + domain);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • a temporary variable is probably a fraction of a millisecond faster I guess, since split() is only run once. – TRGWII Feb 17 '15 at 11:20
  • @TRGWII: Exactly. Or (again) just repeat the `split`, as you've done, if you don't need that fraction of a millisecond. – T.J. Crowder Feb 17 '15 at 11:22