在JavaScript字符串中转义引号 [英] Escaping quotes in a javascript string

查看:462
本文介绍了在JavaScript字符串中转义引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在javascript文本字符串中转义引号(以及撇号和转义字符):

I'm trying to escape the quotes (and apostrofes and escape char) in a text string in javascript:

var text = 'Escape " and \' and /.';
var rx = new RegExp('/([\'"])/g');
console.log(text, ' ==> ', text.replace(rx,'//\1'));​​​​​

我希望输出的是 Escape /和/'和//。,但是我得到 Escape和'和/。

What I expect to be output is Escape /" and /' and //., but instead I get Escape " and ' and /..

我似乎无法正常工作,而且

I just can't seem to get this working and don't know what's wrong.

这里是一个JSFiddle: http:/ /jsfiddle.net/hvtgf/

Here's a JSFiddle: http://jsfiddle.net/hvtgf/

推荐答案

转义表示使用反斜杠 \ 而不是斜杠 /

Escaping means using backslash \ but not slash /.

但是,出于您的目的,您可以尝试以下操作:

However, for your purposes you can try the following:

text.replace(/([/'"])/g, "/$1");

演示: http://jsfiddle.net/hvtgf/1/

这篇关于在JavaScript字符串中转义引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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