PDB
PDB

Reputation: 23

How would I use javascript to seperate a string with two cities (and their states) into their own variables?

I am trying to code a way for this string to be broken into two separate variables. The city name could be one or more words and the state will always follow the last word in the city's name.

var splitFlightInfo = "LOS ANGELES CA MIAMI FL"

var temp;
var theFlightInfo = splitFlightInfo.shift().split(" ");
var theflightDate = theFlightInfo.shift();
var theFlightArrive = theFlightInfo.pop();
var theFlightDepart = theFlightInfo.pop();
var theFlightPorts = splitFlightInfo.shift();

for(var p = 0; p < theFlightInfo.length; p++){
  if(p === 0){
    temp = theFlightInfo[p];
  } else{
    temp += ' '+theFlightInfo[p];
  }
}

Expected Results:

var departPort = "Los Angeles, CA"
var arrivePort = "Miami, FL"

Actual Results: none

Upvotes: 1

Views: 56

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627022

You may match these strings using

/.*?\b[A-Z]{2}\b/g

See the regex demo.

NOTE: If you want to precisely match U.S. states you may replace [A-Z]{2} with (?:AL|AK|AZ|AR|CA|CO|CT|DE|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY):

/.*?\b(?:AL|AK|AZ|AR|CA|CO|CT|DE|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY)\b/g

Pattern details

  • .*? - any 0+ chars other than linebreak chars as few as possible
  • \b[A-Z]{2}\b - a whole word consisting of two uppercase letters.

Then, add a comma before the last 1+ whitespaces + 1+ non-whitrespaces with .replace(/\s+\S+$/, ',$&').

JS demo:

var regex = /.*?\b[A-Z]{2}\b/g;
var str = "LOS ANGELES CA MIAMI FL";
var res = str.match(regex);
console.log(res[0].trim().replace(/\s+\S+$/, ',$&'));
console.log(res[1].trim().replace(/\s+\S+$/, ',$&'));

Upvotes: 1

Related Questions