简体   繁体   English

在 JavaScript 字符串中转义单引号和双引号

[英]Escaping single and double quotes in JavaScript string

my string ${field.value} has values我的字符串${field.value}有值

'<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"我想在some test' and "xyz"转义单引号和双引号some test' and "xyz"

I am trying to make the string safe for inserting into HTML table.我试图使string safe for inserting into HTML table.

Update: values are coming from server, i can't skip the HTML elements in string更新:值来自服务器,我不能跳过字符串中的 HTML 元素

JSFIDDLE : https://jsfiddle.net/e3jehrc5/1/ 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.我猜一些服务器端模板语言在这里填写了${field.value}的值。 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.第一:你不应该动态地动态生成 Javascript,通过 AJAX 或类似的方式获取这个 HTML 片段会是一个更好的主意。

Having said this, since your server is dynamically generating Javascript source code here, it needs to take care to produce syntactically valid code .话虽如此,由于您的服务器在这里动态生成 Javascript 源代码,因此需要注意生成语法上有效的代码 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.您无法在 Javascript 中修复此问题,因为 Javascript 本身已经无效。 Your templating language needs to properly encode the string to be valid Javascript.您的模板语言需要将字符串正确编码为有效的 Javascript。 How to do that exactly depends on your templating system;如何做到这一点完全取决于您的模板系统; here's a PHP example:这是一个 PHP 示例:

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

JSON encoding here produces valid Javascript literals, which is all you're looking for here.此处的 JSON 编码会生成有效的 Javascript 文字,这就是您在此处寻找的全部内容。

Also see The Great Escapism (Or: What You Need To Know To Work With Text Within Text) .另请参阅The Great Escapism(或:使用文本中的文本需要了解的内容)

用这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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