Home > Back-end >  Count groups of four spaces at the start of each line
Count groups of four spaces at the start of each line

Time:11-18

I really want to find the number of spaces before a line (which are actually "tabs" in my case), 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(","))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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(","))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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).
  • Related