1

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?

1
  • .split the string and then assign [0], [1] and [2] is the result to the appropriate constants…? Commented May 22, 2018 at 10:02

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

You can also do it like this

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

console.log(city, state, country);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.