简体   繁体   中英

Escaping single and double quotes in JavaScript string

my string ${field.value} has values

'<table id="tblUserList">            
        <tbody>                 
        <tr>
        <td style="padding: 10px;">some test' and "xyz"</td>
        </tr>
        </tbody
        </table>'

What i have tried is

escapestring = '${field.value}'

escapestring.replace("'", "\'");

document.getElementById("tblUserList").innerHTML  = escapestring ;

Error,it is not working

Uncaught SyntaxError: Invalid regular expression flags

I want to escape single quote and double quote in the some test' and "xyz"

I am trying to make the string safe for inserting into HTML table.

Update: values are coming from server, i can't skip the HTML elements in string

JSFIDDLE : https://jsfiddle.net/e3jehrc5/1/

Any help is appreciated.

Reading between the lines here…

 escapestring = '${field.value}'

I'm guessing some server-side templating language is filling in the value of ${field.value} here. First: you should not dynamically generate Javascript on the fly, it would be a much better idea to fetch this HTML snippet via AJAX or such.

Having said this, since your server is dynamically generating Javascript source code here, it needs to take care to produce syntactically valid code . Right now you're naïvely pasting a string into another string, without regards to the syntactic requirements of what you're producing. You cannot fix this in Javascript, since the Javascript itself is already invalid. Your templating language needs to properly encode the string to be valid Javascript. How to do that exactly depends on your templating system; here's a PHP example:

var html = <?= json_encode($field->value); ?>;

JSON encoding here produces valid Javascript literals, which is all you're looking for here.

Also see The Great Escapism (Or: What You Need To Know To Work With Text Within Text) .

用这个

var escapestring ='<table id="tblUserList"><tbody><tr><td style="padding: 10px;">some test'+"'"+' and "xyz"</td></tr></tbody></table>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM