用Javascript替换引号? [英] Replacing quotation marks in Javascript?

查看:100
本文介绍了用Javascript替换引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在制作的网络应用,我将会收到文本字符串,偶尔会包含引号。因为我将成为document.writing字符串,所以需要将它们更改为撇号或转义。我怎么做,因为当我尝试它似乎不起作用,特别是我认为因为字符串的引号停止脚本的其余部分工作。

For a web app I'm making, I'm going to be getting text strings coming in, occasionally which contain quotation marks. Because I am then going to be document.writing the string, they need to be changed either into apostrophes or escaped. How would I do that, because when I try it doesn't seem to work, specifically I think because the string's quotation marks stop the rest of the script working.

希望这是有道理的,我对此很新,所以这就是为什么它可能没有意义。如果需要,我会尽力澄清。谢谢!

Hope that makes some sense, I'm quite new to this so that's why it might not make sense. I'll try and clarify if need be. Thank you!

推荐答案

为HTML转义它们:

var escapedString = string.replace(/'/g, "'").replace(/"/g, """);

为JS代码转义它们:

var escapedString = string.replace(/(['"])/g, "\\$1");

这篇关于用Javascript替换引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆