ES6 Template Literals - remove \n from the string

允我心安 提交于 2020-01-23 16:47:05

问题


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?


回答1:


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.




回答2:


let literal = `template     literal
               string so many holes`;

literal.replace(/\s+/g, ' ');

This will replace one or more spaces with one space.




回答3:


You can use the String.prototype.replace() method to remove all new lines and spaces after them:

var $div = $(`<div class='proj' id='projects'>
                 <div class='bot-nav'>${txt}</div>
           </div>`.replace(/\n\s+/g, ''));



回答4:


To remove leading and trailing whitespace you'd use .replace

To remove the newlines, you can split/join

var $div = $(`<div class='proj' id='projects'>
             <div class='bot-nav'>${txt}</div>
       </div>`.replace(/^\s+|\s+$/gm, '').split('\n').join(''));

Or make a function

function someFunctionName(str) {
    return str.replace(/^\s+|\s+$/gm, '').split('\n').join('')
}

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


来源:https://stackoverflow.com/questions/40142512/es6-template-literals-remove-n-from-the-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!