0

I'm writing html string in JS with this style:

var html = '\
    <div id="parent">\
        <div id="firstChild"></div>\
        <div id="secondChild"></div>\
    </div>\
';

However, these backslashes creates unexpected whitespaces which cause JS generate unexpected text nodes. How can I remove these whitespaces (with regex may be) ?

2
  • How about append newline to each line? (\n\ instead of \ ) Commented Jan 4, 2015 at 3:45
  • why are you using a escape sign(\ ) without the escape character? if you want a new line, you can do this string = "hello\nworld", which will output as "hello (new line) world". In this way, it can store the new line command in the js without altering the results, but you have to use double quotes for this "\n" and not '\n'. however, it's not neccessory to add new line sign in js since it is stored already when you make a new line in your editor Commented Jan 4, 2015 at 3:49

1 Answer 1

3

The \ is not causing the whitespace, the indentation is.

For example, this variable:

var html = '\
<div id="parent">\
<div id="firstChild"></div>\
<div id="secondChild"></div>\
</div>\
';

will output:

<div id="parent"><div id="firstChild"></div><div id="secondChild"></div></div>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Brett. Your answer is good enough for me. I should've washed my face before asking this question. ~~
Ha, we've all been there. Glad you got it worked out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.