Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

76
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!