Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

78
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda