Escape quotes in JavaScript

JavascriptQuotesEscaping

Javascript Problem Overview


I'm outputting values from a database (it isn't really open to public entry, but it is open to entry by a user at the company -- meaning, I'm not worried about XSS).

I'm trying to output a tag like this:

<a href="" onclick="DoEdit('DESCRIPTION');">Click Me</a>

DESCRIPTION is actually a value from the database that is something like this:

Prelim Assess "Mini" Report

I've tried replacing " with ", but no matter what I try, Firefox keeps chopping off my JavaScript call after the space after the word Assess, and it is causing all sorts of issues.

I must bemissing the obvious answer, but for the life of me I can't figure it out.

Anyone care to point out my idiocy?

Here is the entire HTML page (it will be an ASP.NET page eventually, but in order to solve this I took out everything else but the problem code)

<html>
    <body>
        <a href="#" onclick="DoEdit('Preliminary Assessment \"Mini\"'); return false;">edit</a>
    </body>
</html>

Javascript Solutions


Solution 1 - Javascript

You need to escape the string you are writing out into DoEdit to scrub out the double-quote characters. They are causing the onclick HTML attribute to close prematurely.

Using the JavaScript escape character, \, isn't sufficient in the HTML context. You need to replace the double-quote with the proper XML entity representation, &quot;.

Solution 2 - Javascript

&quot; would work in this particular case, as suggested before me, because of the HTML context.

However, if you want your JavaScript code to be independently escaped for any context, you could opt for the native JavaScript encoding:
' becomes \x27
" becomes \x22

So your onclick would become:
DoEdit('Preliminary Assessment \x22Mini\x22');

This would work for example also when passing a JavaScript string as a parameter to another JavaScript method (alert() is an easy test method for this).

I am referring you to the duplicate Stack Overflow question, How do I escape a string inside JavaScript code inside an onClick handler?.

Solution 3 - Javascript

<html>
    <body>
        <a href="#" onclick="DoEdit('Preliminary Assessment &quot;Mini&quot;'); return false;">edit</a>
    </body>
</html>

Should do the trick.

Solution 4 - Javascript

Folks, there is already the unescape function in JavaScript which does the unescaping for \":

<script type="text/javascript">
    var str="this is \"good\"";
    document.write(unescape(str))
</script>

Solution 5 - Javascript

The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.

<a href="#" onclick='DoEdit("Preliminary Assessment \"Mini\""); return false;'>edit</a>

Solution 6 - Javascript

This is how I do it, basically str.replace(/[\""]/g, '\\"').

var display = document.getElementById('output');
var str = 'class="whatever-foo__input" id="node-key"';
display.innerHTML = str.replace(/[\""]/g, '\\"');

//will return class=\"whatever-foo__input\" id=\"node-key\"

<span id="output"></span>

Solution 7 - Javascript

If you're assembling the HTML in Java, you can use this nice utility class from Apache commons-lang to do all the escaping correctly:

> org.apache.commons.lang.StringEscapeUtils
Escapes and unescapes > Strings for Java, Java Script, HTML, XML, and SQL.

Solution 8 - Javascript

I have done a sample one using jQuery

var descr = 'test"inside"outside';
$(function(){
   $("#div1").append('<a href="#" onclick="DoEdit(descr);">Click Me</a>');       
});
        
function DoEdit(desc)
{
    alert ( desc );
}

And this works in Internet Explorer and Firefox.

Solution 9 - Javascript

Please find in the below code which escapes the single quotes as part of the entered string using a regular expression. It validates if the user-entered string is comma-separated and at the same time it even escapes any single quote(s) entered as part of the string.

In order to escape single quotes, just enter a backward slash followed by a single quote like: \’ as part of the string. I used jQuery validator for this example, and you can use as per your convenience.

Valid String Examples:

'Hello'

'Hello', 'World'

'Hello','World'

'Hello','World',' '

'It's my world', 'Can't enjoy this without me.', 'Welcome, Guest'

HTML:

<tr>
    <td>
        <label class="control-label">
            String Field:
        </label>
        <div class="inner-addon right-addon">
            <input type="text" id="stringField"
                   name="stringField"
                   class="form-control"
                   autocomplete="off"
                   data-rule-required="true"
                   data-msg-required="Cannot be blank."
                   data-rule-commaSeparatedText="true"
                   data-msg-commaSeparatedText="Invalid comma separated value(s).">
        </div>
    </td>

JavaScript:

     /**
 *
 * @param {type} param1
 * @param {type} param2
 * @param {type} param3
 */
jQuery.validator.addMethod('commaSeparatedText', function(value, element) {

    if (value.length === 0) {
        return true;
    }
    var expression = new RegExp("^((')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))(((,)|(,\\s))(')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))*$");
    return expression.test(value);
}, 'Invalid comma separated string values.');

Solution 10 - Javascript

You can copy those two functions (listed below), and use them to escape/unescape all quotes and special characters. You don't have to use jQuery or any other library for this.

function escape(s) {
    return ('' + s)
        .replace(/\\/g, '\\\\')
        .replace(/\t/g, '\\t')
        .replace(/\n/g, '\\n')
        .replace(/\u00A0/g, '\\u00A0')
        .replace(/&/g, '\\x26')
        .replace(/'/g, '\\x27')
        .replace(/"/g, '\\x22')
        .replace(/</g, '\\x3C')
        .replace(/>/g, '\\x3E');
}

function unescape(s) {
    s = ('' + s)
       .replace(/\\x3E/g, '>')
       .replace(/\\x3C/g, '<')
       .replace(/\\x22/g, '"')
       .replace(/\\x27/g, "'")
       .replace(/\\x26/g, '&')
       .replace(/\\u00A0/g, '\u00A0')
       .replace(/\\n/g, '\n')
       .replace(/\\t/g, '\t');

    return s.replace(/\\\\/g, '\\');
}

Solution 11 - Javascript

Escape whitespace as well. It sounds to me like Firefox is assuming three arguments instead of one. &nbsp; is the non-breaking space character. Even if it's not the whole problem, it may still be a good idea.

Solution 12 - Javascript

You need to escape quotes with double backslashes.

This fails (produced by PHP's json_encode):

<script>
  var jsonString = '[{"key":"my \"value\" "}]';
  var parsedJson = JSON.parse(jsonString);
</script>

This works:

<script>
  var jsonString = '[{"key":"my \\"value\\" "}]';
  var parsedJson = JSON.parse(jsonString);
</script>

Solution 13 - Javascript

You can use the escape() and unescape() jQuery methods. Like below,

Use escape(str); to escape the string and recover again using unescape(str_esc);.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt DawdyView Question on Stackoverflow
Solution 1 - JavascriptAaronView Answer on Stackoverflow
Solution 2 - JavascripttsemerView Answer on Stackoverflow
Solution 3 - JavascriptkristianView Answer on Stackoverflow
Solution 4 - JavascriptrohtakdevView Answer on Stackoverflow
Solution 5 - Javascriptdl.View Answer on Stackoverflow
Solution 6 - JavascriptRonnie RoystonView Answer on Stackoverflow
Solution 7 - JavascriptiTakeView Answer on Stackoverflow
Solution 8 - JavascriptrahulView Answer on Stackoverflow
Solution 9 - JavascriptDinesh LomteView Answer on Stackoverflow
Solution 10 - JavascriptomanosoftView Answer on Stackoverflow
Solution 11 - Javascriptthe HampsterView Answer on Stackoverflow
Solution 12 - JavascriptBuffaloView Answer on Stackoverflow
Solution 13 - JavascriptAbhiramView Answer on Stackoverflow