admin 管理员组

文章数量: 1086019

How to create the following variables:

const city = 'Your city';
const state = 'your state';
const country = 'Country';

From the input variable

const address = "Your city, your state, your country";

Are there any methods to do this in JavaScript?

How to create the following variables:

const city = 'Your city';
const state = 'your state';
const country = 'Country';

From the input variable

const address = "Your city, your state, your country";

Are there any methods to do this in JavaScript?

Share Improve this question edited May 22, 2018 at 15:03 Luca Kiebel 10.1k7 gold badges32 silver badges46 bronze badges asked May 22, 2018 at 10:00 Midhun JayanMidhun Jayan 2232 silver badges10 bronze badges 1
  • .split the string and then assign [0], [1] and [2] is the result to the appropriate constants…? – deceze Commented May 22, 2018 at 10:02
Add a ment  | 

3 Answers 3

Reset to default 6

There are a lot of ways to tackle this problem. If the string is always in the format of value1 <ma> value2 <ma> value3 you can easily use String.prototype.split() to get an array from the String and then assign the constants to the array indexes:

let address = "Your city, your state, your country";

address = address.split(", ");

const city = address[0];
const state = address[1];
const country = address[2];

console.log(city, state, country);

With ES6 you can use destructuring assignments to make this even shorter:

let address = "Your city, your state, your country";

address = address.split(", ");

const [city, state, country] = address;

console.log(city, state, country);

Try this.

    const address = "Your city, your state, your country";
    const splits = address.split(", ");

    const city = splits[0];
    const state = splits[1];
    const country = splits[2];

You can also do it like this

const { 2: city, 3: state, 4: country } = address.split(', ');

console.log(city, state, country);

本文标签: javascriptDynamic variable creation using constStack Overflow