0

When I'm building HTML in JavaScript I'm constantly escaping double quotes. E.g.

$(wrapper).append("<input type=\"text\" name=\"thingummy[" + id + "]\" data-id=\"" + data_id + "\" id=\"" + id + "_" + data_id + "\" /> <br>"); 

and, when there are many quotation marks, I'm constantly making mistakes over which quotes I've escaped. And I end up spending more time than I'd like fixing them.

Is there a better (quicker / safer / more legible) way of building HTML than the approach I'm using?

UPDATE

One rather important point I forgot to mention! I'm outputting this JavaScript using PHP. So, I have code like this:

echo '$(wrapper).append("<input type=\"text\" name=\"thingummy[" + id + "]\" data-id=\"" + data_id + "\" id=\"" + id + "_" + data_id + "\" /> <br>");';

which makes using single quotation marks a problem ('cos they end up breaking the PHP! Which is another problem I keep experiencing when I forget I'm in the middle of some PHP and use a single quotation mark as mentioned in a comment below).

3
  • 3
    In this you could just have single quotes $(wrapper).append('...'). You can also use the HTML quotes (&quot;) as well in a general case. Commented Sep 23, 2016 at 23:11
  • See my UPDATE. The whole thing is wrapped in single quotation marks. Commented Sep 23, 2016 at 23:20
  • Then use a HERE doc in PHP instead of a string. Commented Sep 24, 2016 at 3:37

2 Answers 2

1

You could perhaps use templating strings in JavaScript. Makes it simple to insert variables into a string too with ${var} syntax.

echo '$(wrapper).append(`<input type="text" name="thingummy[${id}]" data-id="${data_id}" id="${id}_${data_id}" /> <br>`);';
Sign up to request clarification or add additional context in comments.

Comments

0

You could use heredoc syntax like this:

<?php
echo <<<JAVASCRIPT
<script type="text/javascript">
alert("some javascript code where you don't have to escape double quotes");
</script>
JAVASCRIPT;

This would simplify you work.

Or you can close your php tag and open it again, like this:

<?php
$somePhpCode = 1;
?>
<script type="text/javascript">
alert("some javascript code where you don't have to escape double quotes");
</script>
<?php
$somePhpCode = 2;
?>

Comments

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.