Midhun Jayan
Midhun Jayan

Reputation: 223

Dynamic variable creation using const

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?

Upvotes: 1

Views: 3539

Answers (3)

Luca Kiebel
Luca Kiebel

Reputation: 10096

There are a lot of ways to tackle this problem. If the string is always in the format of value1 <comma> value2 <comma> 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);

Upvotes: 6

Midhun Jayan
Midhun Jayan

Reputation: 223

You can also do it like this

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

console.log(city, state, country);

Upvotes: 2

Anuradha Gunasekara
Anuradha Gunasekara

Reputation: 6983

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];

Upvotes: 2

Related Questions