Okan Kocyigit
Okan Kocyigit

Reputation: 13441

Escaping quote in JavaScript and PHP

<?php
    /* ... Getting record from database */

    $comment = $record["comment"];
    /* There might be quotes or double quotes, we don't know */

    echo "<input type='button' onclick=\"doSomething('$comment')\" />";
?>

<script>
    function doSomething(comment) {
        alert(comment);

        /* Something else */
    }
</script>

When $comment string contains a single quote , I'm getting "Uncaught SyntaxError: Unexpected token ILLEGAL" error in javascript.

How can I escape quote and double quote in this example?

Upvotes: 0

Views: 2269

Answers (3)

rogerlsmith
rogerlsmith

Reputation: 6786

Use the PHP function addslashes().

Upvotes: 2

Marc B
Marc B

Reputation: 360842

Use json_encode(), which guarantees your output will be syntactically valid JavaScript code:

<input type="button" onclick="doSomething(<?php echo json_encode($comment) ?>">

Upvotes: 9

Simon Arnold
Simon Arnold

Reputation: 16177

You can try something like this in Javascript:

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

Hope this help :)

Upvotes: 0

Related Questions