Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

304
Visualizações
How to pluck the second value in a url after the first slash, in a string that could have many slashes?

I know there are countless regex questions out there, but I was unable to find one that fits my situation.

Suppose I have the following pathname:

/u/some_user/create/initial

How can I extract 'some_user' from this string?

I got pretty close with this:

const pathname = '/u/some_user/create/initial';

const result = pathname.match(/(\/u\/)(.{1,}\/)(.+)/);

console.log('result', result);

This could potentially work if the string was '/u/some_user/create' -- It would return some_user/, and I could filter out the slash at the end. But if the string has more slashes, as above, then this just returns 'some_user/create/'.

How can I achieve plucking out just 'some_user'?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use a capture group and a negated character class:

\/u\/([^/]+)

Explanation

  • \/u\/ Match /u/
  • ( Capture group 1
    • [^/]+ Match 1+ characters other than / using a negated character class.
  • ) Close group 1

See a regex101 demo.

const regex = /\/u\/([^/]+)/;
[
  "/u/some_user/create/initial",
  "/u/some_user/create",
  "test/123/u/some_user/a/b/c"
].forEach(s => {
  const m = s.match(regex);
  if (m) {
    console.log(m[1]);
  }
});

If you don't want to cross newlines, and there has to be a / after some_user:

\/u\/([^/\s]+)\/

See another regex 101 demo.

about 4 years ago · Juan Pablo Isaza Relatório

0

If you don't care about legacy browser support, which includes Safari and any browser installed on Mac/iOS, then this would work:

/(?<=^\/u\/)[^\/]+/

var regexp = /(?<=^\/u\/)[^\/]+/;

console.log( `/u/some_user/create/initial`.match( regexp ) );
console.log( `/u/`.match( regexp ) );
console.log( `/wrong/format/url`.match( regexp ) );
console.log( `/u/another_user/create/initial`.match( regexp ) );

https://regex101.com/r/NmtKxD/1

about 4 years ago · Juan Pablo Isaza Relatório

0

Not withstanding the request for a regular expression, the specific problem is easily solved with either of two common string methods.

string.split

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

Returns an array of substrings demarked according to any character or characters provided as an argument. By splitting the string at each of the slashes, the required string is element[2] of the resulting array (since element [0] will be empty -being derived from 0 characters before the first "/").

viz:

const url = "/u/some_user/create/initial";

requiredString = url.split("/")[2];

console.log(requiredString); // "some_user";

string slice

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

Where the position, either numerically or by reference to known bounding test, of the target substring is available, string.slice provides an easy method to extract the required substring.

In this example bounding text parts are used to extract the required field:

const url = "/u/some_user/create/initial";

beforeText = "/u/";
afterText = "/create";

let requiredString = url.slice(url.indexOf(beforeText)+beforeText.length, url.indexOf(afterText));

console.log(requiredString); // "some-user"

Both of these methods are reliable core javascript, supported by all interpreters.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda