locked
How to extract country code from url using regex RRS feed

  • Question

  • User1183902823 posted

    i want to extract country code from url using regex with javascript.

    i tried this but did not worked

    var reg = ^\/[a-zA-Z]{2}\/;
    var countrycode = reg.exec( 'http://mysite.com/gb/index.aspx' )[1];
    
    alert(countrycode);

    gb is the country code in my url. give me the right code.

    Saturday, November 25, 2017 8:09 PM

Answers

  • User2103319870 posted

    extract country code from url using regex with javascript

    You can try with the below code

    //Your url
    var url = "http://mysite.com/gb/index.aspx";
    //Get the language code
    var countrycode = /com\/([^\/]+)/.exec(url)[1];
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, November 25, 2017 11:46 PM
  • User1183902823 posted

    this code worked.

    var url="http://mysite:2020/gb/index.aspx";
    alert(url.split('/')[3]);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, November 26, 2017 12:10 PM

All replies

  • User2103319870 posted

    extract country code from url using regex with javascript

    You can try with the below code

    //Your url
    var url = "http://mysite.com/gb/index.aspx";
    //Get the language code
    var countrycode = /com\/([^\/]+)/.exec(url)[1];
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, November 25, 2017 11:46 PM
  • User1183902823 posted

    thanks for your code

    var url = "http://mysite.com/gb/index.aspx";
    //Get the language code
    var countrycode = /com\/([^\/]+)/.exec(url)[1];
    alert(countrycode);

    i test your code it works but when i run my site from VS2013 IDE then url looks like http://localhost:2020/gb/index.aspx and when browser the same site from local iis then url look like http://mysite:2020/gb/index.aspx

    so i want js code in such a way whatever my url i want to extract country code.

    so my possible url would be

    http://mysite.com/gb/index.aspx

    http://localhost:2020/gb/index.aspx

    http://mysite:2020/gb/index.aspx

    so please give me a rectified version of code which works fine for above 3 url.

    thanks

    Sunday, November 26, 2017 11:36 AM
  • User1183902823 posted

    this code worked.

    var url="http://mysite:2020/gb/index.aspx";
    alert(url.split('/')[3]);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, November 26, 2017 12:10 PM