Rupam
Rupam

Reputation: 77

Regex to extract city and city code from a dynamic URL in React

I am storing the URL in location variale ,and which will be dynamic for ex.

1- https://abc.go.com/United_States,US/

2- https://abc.go.com/US/

3- https://abc.go.com/Uganda,UG/

4- https://abc.go.com/United_States,US

5- https://abc.go.com/

the URL's are totally dynamic , I was able to extract the state Code with following regex :-

const cityCode =location.split(/(?=[A-Z][A-Z])/)[1].split('/')[0];

//this will get two consecutive Uppercase characters and remove "/" in the end if present

Is there any possible regex to extract the country and State Code in a single variable if present in the url.

Upvotes: 1

Views: 208

Answers (3)

The fourth bird
The fourth bird

Reputation: 163427

You can use a capture group with an optional part for the first part and the comma

https?:\/\/\S+?\/((?:\w+,)?[A-Z][A-Z])
  • https?:\/\/ Match the protocol with optional s
  • \S+?\/ Match 1+ non whitespace chars as least as possible
  • ( Capture group 1 (Which is accessed by m[1] in the example code)
    • (?:\w+,)? Optionally match 1+ word characters and a comma
    • [A-Z][A-Z] Match 2 uppercase chars
  • ) Close group 1

Regex demo

const pattern = /https?:\/\/\S+?\/((?:\w+,)?[A-Z][A-Z])/;
[
  "https://abc.go.com/United_States,US/",
  "https://abc.go.com/US/",
  "https://abc.go.com/Uganda,UG/",
  "https://abc.go.com/United_States,US",
  "https://abc.go.com/"
].forEach(s => {
  const m = s.match(pattern);
  console.log(m ? m[1] : "no match");
});

Or if it is the part after the first forward slash

https?:\/\/[^\s\/]+\/((?:\w+,)?[A-Z][A-Z])

Regex demo

Upvotes: 2

Hemendra Singh
Hemendra Singh

Reputation: 11

var pathName = location.pathname;
var countryCode = (pathName.split('/')).length!= 0 ? pathName.split('/')[1].split(',') : [];
console.log(countryCode);


// if the Window URL is - "https://test.org/United_States,US" then result is - ["United_States", "US"]

// if the Window URL is - "https://test.org/United_States" then result is - ["United_States"]

Upvotes: 1

Umair Khan
Umair Khan

Reputation: 1752

Reference: String.prototype.match()

urls = ['https://abc.go.com/United_States,US/',
  'https://abc.go.com/US/',
  'https://abc.go.com/Uganda,UG/',
  'https://abc.go.com/United_States,US',
  'https://abc.go.com/'
];
urls.forEach(url => {
  console.log(url.match(/.*:\/\/.*?\/(.*)/m)[1].replace(/\/$/, ''))
});

Upvotes: 2

Related Questions