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
};
2
  • 2
    What are those special characters? Commented Apr 14, 2011 at 18:23
  • And how do you assign those characters and what error do you get? Commented Apr 14, 2011 at 18:26

3 Answers 3

2

The escape function or the newer encodeURIComponent.

Sign up to request clarification or add additional context in comments.

2 Comments

escape is not a standard function.
@Gumbo true, but all major browsers support it. That said I agree and recommend encodeURIComponent if it is available on the target browsers.
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.

Comments

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.

2 Comments

I escaped <p> as \<p> and didn't escaped </p> so it looks like works. Do I do anything wrong?
@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.

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.