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

82
Visualizações
Count groups of characters at the start of each line

I really want to find the number of spaces before a line (which are actually "tabs" in my case but no really), and I have a piece of code that seems to work, but it's really bad and slow. Please view it below:

var data = "test\n    another test\none more"
var tabs = []
data.split("\n").forEach((line, index) => {
  tabs[index] = Math.floor((line.length - line.replace(/^(.*?)[^\ ]/g, "").length) / 4)
})
alert(tabs.join(", "))

Also, only need a way to find groups of four spaces, if that's possible. Is there a way to do that the fastest?

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

0

You can use

data.split('\n').map(x => (x.match(/ {4}/gy) || []).length);

See an updated demo:

var data = "test\n    another test\n        one more";
var tabs = data.split('\n').map(x => (x.match(/ {4}/gy) || []).length);
console.log(tabs.join(","))

Here,

  • .split('\n') - splits the string into lines
  • .map(x => (x.match(/ {4}/gy) || []).length) - gets each line and applies the .match(/ {4}/gy) on it. / {4}/gy matches all, multiple occurrences (due to g flag) of four spaces from the start of string, and the next match only occurs exactly after the previous match (thanks to the sticky y flag).
  • The (... || []).length gets either the count of matched groups of four spaces or 0 if there was no match (|| [] ensures we get zeros without exceptions).
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