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

252
Visualizações
JS String how to extract an array of substring that matches a condition?

I have a string like this:

"|hello| + |world| / |again|"

And I need to get the substrings inside the | and return an array like this:

["hello", "world", "again"]

What is the best approach to accomplish this?

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

0

You can use a regex that searches for groups consisting only of letters (([A-Za-z])) between pipes (/|) where the pipes are to omitted from the actual match (wrapped with (?:))-- then use .matchAll to get all the matches and .map the result to get the captured groups only (non-captures omitted) -- see below:

const str = "|hello| + |world| / |again|";

const re = /(?:\|)([A-Za-z]+)(?:\|)/g;

const results = [...str.matchAll(re)].map((entry) => entry[1]);

console.log(results);

This will work to match only those words that are between pipes. If you have other words in your string that are not wrapped between pipes, they will be ignored. Like the following snippet:

const str = "|hello| + |world| / |again| how are |you| doing?";

const re = /(?:\|)([A-Za-z]+)(?:\|)/g;

const results = [...str.matchAll(re)].map((entry) => entry[1]);

console.log(results);

about 4 years ago · Juan Pablo Isaza Relatório

0

array = [];
let name = "";
let input = "|hello| + |world| / |again|";
let index = 0;
let isStart = false;

while (index < input.length) {
  if (input[index] == '|') {
    isStart = !isStart;
    if (!isStart) {
      array.push(name);
      name = "";
    }
  } else {
    if (isStart) {
      name = name + input[index];
    }
  }
  index++;
}
console.log(array);

about 4 years ago · Juan Pablo Isaza Relatório

0

If that string doesn't change format use a regular expression to match against multiple lower-case letters.

const str = '|hello| + |world| / |again|';
const regex = /[a-z]+/g;
console.log(str.match(regex));

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