Home > Back-end >  Regex for replacing all whitespaces to tab characters at the beginning of each line
Regex for replacing all whitespaces to tab characters at the beginning of each line

Time:11-18

I want to replace all 2 white space characters with one tab character (\t) at the beginning of each line. As shown in the example below, white spaces between non-white space (comment line) should not be replaced.

I want to convert this:

int main() {
  if (true)
    cout << "Hi";  // comment
}

to this:

int main() {
\tif (true)
\t\tcout << "Hi";  // comment
}

This regex I come up with catches only one whitespace pair per line:

^(\s\s)

CodePudding user response:

You can search for all leading spaces and use a callback to compute the length of the replacement

src = `
int main() {
  if (true)
    cout << "Hi";  // comment
}
`

tabs = src.replace(/^  /gm, s => '\t'.repeat(s.length / 2))

console.log(tabs)

  • Related