Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Template Literals - remove \n from the string

I'm changing my multiline variables to Template Literals and it's amazing, but then I noticed that the indents I do are converted (minified) into \n with the indentation I did on the original code. How can I avoid that?

Ex:

var $div = $(`<div class='proj' id='projects'>
                 <div class='bot-nav'>${txt}</div>
           </div>`);

It's converted to:

var $div = $("<div class='proj' id='projects'>\n                 <div class='bot-nav'>"+txt+"</div>\n           </div>");

And I want this:

var $div = $("<div class='proj' id='projects'><div class='bot-nav'>"+txt+"</div></div>");

Is there any way to do this?

like image 327
sandrina-p Avatar asked Oct 19 '16 22:10

sandrina-p


People also ask

How do you break a line in template literal?

To escape a backtick in a template literal, put a backslash ( \ ) before the backtick.

What is `` in JS?

Backticks ( ` ) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier. Features: we can interpolate any kind of expression in the template literals. They can be multi-line.

What are template literals in ES6?

Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions. Before ES6, template literals were called as template strings.


1 Answers

While using .replace (like suggested in other answers) will work, it is not the cool new shiny way of doing it ;)

I think what you are looking for is a literal tag function (aka "Tagged Templates"), introduced in ES2015.

There are a bunch of them here:

https://github.com/declandewet/common-tags

And you would probably want oneLine (or oneLineTrim):

oneLine`
  foo
  bar
  baz
`
// "foo bar baz"

Note: oneLine, obviously, uses replace internally.

like image 178
Liel Avatar answered Oct 02 '22 07:10

Liel