2

I want to assign an HTML string to a JavaScript variable but it gives error because of special characters. Is there any easy way to escape that characters?

What I want to do at my js file:

var messageTemplate = {
   defaultMessageTemplate : "<p>aaaa <b>_username_</b>,</p>
            <p>1sdfasşlğllğlğ.</p>
            <p><b>1 sdfsfsfü şesdfce 12 sfsf.</b></p>
            <p>Üsdfdsfsfsf üyelesfdsdfsdfmsdfdsfdava.</p>
            <p style="font-weight:bold; font-size: 16px;"><a href="/dsfsfs">sfsdfsf Yarasfsdfklayın</a></p>
        <p>Önsdfdsfpıİsdfdfsfn kaçırmayın.</p>
        <br/> <br/>fafaf, <br/>_domain_ Ekssibi</textarea></label></td>"
.... code continues here
};
cytinus
  • 5,467
  • 8
  • 36
  • 47
kamaci
  • 72,915
  • 69
  • 228
  • 366

3 Answers3

2

use the escape function: http://www.devguru.com/technologies/ecmascript/quickref/escape.html

but be warned that this escapes everything. It depends on what you want to do with that html in the variable.

Munzilla
  • 3,805
  • 5
  • 31
  • 35
2

The escape function or the newer encodeURIComponent.

Adam
  • 43,763
  • 16
  • 104
  • 144
  • `escape` is not a standard function. – Gumbo Apr 14 '11 at 18:26
  • 1
    @Gumbo true, but all major browsers support it. That said I agree and recommend `encodeURIComponent` if it is available on the target browsers. – Adam Apr 14 '11 at 18:55
1

You need to escape the " inside the string quoted with " using \":

var messageTemplate = {
   defaultMessageTemplate : "<p>aaaa <b>_username_</b>,</p>
            <p>1sdfasşlğllğlğ.</p>
            <p><b>1 sdfsfsfü şesdfce 12 sfsf.</b></p>
            <p>Üsdfdsfsfsf üyelesfdsdfsdfmsdfdsfdava.</p>
            <p style=\"font-weight:bold; font-size: 16px;\"><a href=\"/dsfsfs\">sfsdfsf Yarasfsdfklayın</a></p>
        <p>Önsdfdsfpıİsdfdfsfn kaçırmayın.</p>
        <br/> <br/>fafaf, <br/>_domain_ Ekssibi</textarea></label></td>"
};

Or use single quotes where you can use " without escaping them (but you would need to escape '):

var messageTemplate = {
   defaultMessageTemplate : '…'
};

And if this JavaScript code is embedded into HTML, you also need to escape the </ somehow.

Community
  • 1
  • 1
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • I escaped

    as \

    and didn't escaped

    so it looks like works. Do I do anything wrong?
    – kamaci Apr 14 '11 at 18:57
  • @kamaci: No, you need to “remove” the literal `` somehow and that only when embedding it into HTML as that’s interpreted as end tag open delimiter of the `SCRIPT` element. – Gumbo Apr 14 '11 at 18:59