skip to Main Content

I want to parse the 2 first elements of a URL with JavaScript.

For ex.

url.de/de/de/produkte/

I want to parse de/de, I have following code

function(){
  var path={{Page Path}};
  return path.match(/^/(w+)(?:/|$)/)[1]
}

but the result is just de, hope for a easy solution.

I’ve tried a inline JavaScript

2

Answers


  1. Parenthesis surrounding expression is looking for: 2 characters of a-z then / then 2 characters again.

    function () { 
      var path={{Page Path}}; 
    
      // output of path.match: `["/de/de/","de/de"]` 
      // and return 2nd item
      return path.match(//([a-zA-Z]{2}/[a-zA-Z]{2})//)[1];
    }
    
    Login or Signup to reply.
  2. If you are looking for an alternative way without using pregmatch you can try something like this to parse the first to parts of the URL. For this answer its necessary for the searched string to be on the same position every time.

    let url = 'test.com/de/de/asdf/123';
    
    let parts = url.split('/');
    
    let languageCodes = parts[1] + '/' + parts[2];
    

    If you want to use pregmatch try something like this [a-z]{2}/[a-z]{2}/ and replace the last ‘/’ with .replace(‘/’,”); to get rid of it.

    The Numbers in curly brackets are for the length of the searched part so if its only country codes it should be fine with sticking with 2.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search