Search code examples
regexhighlightjs

Regex delete spaces from every line start


I use Highlight js plugin which auto indents my code. My IDE also auto indents my code.

<div>
     <div>
         <pre>
              <code>
                   <h1>Hello world</h1>
              </code>
         </pre>
      </div>
 </div>

I would like to have this :

<h1>Hello word</h1>

But because Highlight js does not do relative indetation I end up with this :

                   <h1>Hello world</h1>

So I tried something like this

$('pre code').html($('pre code').html().replace(/^\s{24,}/g,''));

And it's working fine for the first line of the string but I would like to do this on every line --> Remove every 24 first white spaces from every line start.


Solution

  • Two things:

    • \s matches newlines, too, so you need a [^\S\r\n] to match any horizontal space
    • The /m modifier is required to make ^ match the beginning of a line, not of a whole string.

    Since I counted only 19 spaces in your above sample, here is a working regex:

    /^[^\S\r\n]{19,}/gm
    

    See the regex demo