Search code examples
javascriptregextabsremoving-whitespace

Regex for replacing all whitespaces to tab characters at the beginning of each line


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)

Solution

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