I
I
Igor Popov2019-02-14 12:18:07
JavaScript
Igor Popov, 2019-02-14 12:18:07

How to get /url/ from /url1/url2/url3 using regular expression in JS (instead of text.split('/')[1])?

Hello, I can solve this problem in this way
text.split('/')[1]
but I want a more elegant solution using regexp, tell me how this can be done, and what does each character mean in such a regexp solution.
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2019-02-14
@Casufi

Regular expressions are far from being an elegant solution. They are too heavy for such a simple task.
shop.oreilly.com/product/9780596528126.do

P
Pavel Kornilov, 2019-02-14
@KorniloFF

Here, I sketched a function that parses a string with a URL, maybe. useful:

function parseURL (url) {
  var pU = url.split('/')
  .filter((i, ind, arr)=> i.length && i.indexOf('?') === -1),
      search = url.split('?')[1] || null,
    s = search && search.split('&').reduce((a,c) => {
      var i = c.split('=');
      a[i[0]]= i[1];
      return a;
    }, {});

  return {
    protocol: pU[0].slice(0,-1),
    host: pU[1],
    pathname: '/' + pU.slice(2).join('/') + '/',
    searchFull: '?' + search,
    search: s
  }
}

console.log(parseURL ('https://codepen.io/KorniloFF/pen/qgMVem?editors=0012'));

https://codepen.io/KorniloFF/pen/qgMVem?editors=0012

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question