Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript remove whitespaces in `strings`

I JavaScript the ` is very useful when writing big strings. My problem is that it takes into account the amount of white space before it in the JavaScript. So if your string is indented in the JavaScript, then it will be indented in the string as well. Is there any way to get rid of this?

Because in an example like this I would like the html tag to be flush against the left side in the string, but I do not want to make it flush against the left side in the JavaScript. Check how the console.log turns out to understand it better.

MyFunction = function() {
  console.log(`
    <html>
      <head>
      </head>
      <body>
      </body>
    </html>
  `);
}

MyFunction();

console.log:

enter image description here

like image 301
Freddy Bonda Avatar asked Jun 09 '26 09:06

Freddy Bonda


1 Answers

Since you want them html tag to be flush against the left side, but still want head and body indented relatively, what you're looking for is to replace set of 4 spaces in the beginning of each line with an empty string.

string.replace(/^ {4}/gm, '')

Here's the live code ..

MyFunction = function() {
  console.log(`
    <html>
      <head>
      </head>
      <body>
      </body>
    </html>
  `.replace(/^ {4}/gm, ''));
}

MyFunction();
like image 152
rmn Avatar answered Jun 11 '26 23:06

rmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!