How to escape or replace apostrophe and quotation mark in javascript variables?

I have an ASP.NET web page with javascript that manipulates variables that may contain apostrophes and quotation marks. As you might imagine, these characters are causing script errors because they are terminating the string. I tried escaping them with this function:

function escapeCharacters(str)
{
      str = str.replace(/""/g, '\\""');
      str = str.replace(/'/g, ""\\'"");
      return str;
}

This improves things but still causes issues in certain scenarios. (Specifically, the javascript within the ComponentArt Grid control's client templates do not seem to be respecting the escaped quotation mark.)

Is there a more reliable way to escape these characters? Or perhaps another approach is warranted - how about replacing the apostrophe and quotation mark with two benign characters that always play nice? But which characters? I need to round trip the values so I need to choose two characters that won't ever be legitimately present. This is an international application where a wide variety of languages may be present.
LVL 6
rdogmartinAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

fsze88Commented:
try this
<script type="text/javascript">

function escapeCharacters(str)
{
      str = str.replace(/"/g, '\\\"').replace(/\'/g, "\\'");
      return str;
}
//document.write('abc"def\'xyz'+'<br/>');
document.write(escapeCharacters('abc"def\'xyz')+'<br/>');
</script>
0
rdogmartinAuthor Commented:
Unfortunately, that did not make any difference. I spent some time to reduce the issue down to the simplest scenario:

<p id="pTest"></p>
<script type="text/javascript">
    var roleName = 'role\"name';
    var roleNameEscaped = escapeCharacters(roleName);
    var str = '<a href="javascript:alert(\'' + roleNameEscaped + '\');">Test</a>';
   
    document.getElementById('pTest').innerHTML = str;
   
    function escapeCharacters(str)
    {
        str = str.replace(/"/g, '\\\"').replace(/\'/g, "\\'");
        return str;
    }
</script>

The script writes a hyperlink to the <p> tag that, when clicked, shows an alert displaying the contents of the roleName variable. When roleName contains a quotation mark, as shown above, the script fails.

I cannot figure out how to escape the quote inside the roleName variable so that the script works.

0
fsze88Commented:
how about this

<p id="pTest"></p>
abc
<script type="text/javascript">
   var roleName = 'role\"name\'abc';
   var roleNameEscaped = escapeCharacters(roleName);
   var str = '<a href="javascript:alert(\'' + roleNameEscaped + '\');">Test</a>';
   document.getElementById('pTest').innerHTML = str;
   function escapeCharacters(str)
   {
       str = str.replace(/\"/g, escape("\"")).replace(/\'/g, escape("\""));
       return str;
   }
</script>

Open in new window

0
rdogmartinAuthor Commented:
Thanks for turning me on to the escape function! That got me pointed in the right direction, and I ended up with the following. I replaced escape with encodeURI because escape is deprecated, and I tweaked your sample so that apostrophes remain apostrophes instead of being converted to quotation marks.

In the end it works!

<p id="pTest"></p>
abc
<script type="text/javascript">
   var roleName = 'role\"name\'abc';
   var roleNameEscaped = escapeCharacters(roleName);
   var str = '<a href="javascript:alert(\'' + roleNameEscaped + '\');">Test</a>';
   document.getElementById('pTest').innerHTML = str;
   function escapeCharacters(str)
   {
        return encodeURI(roleName.replace(/"/g, '\\\"').replace(/\'/g, "\\'"));
   }
</script>




0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.