如何从javascript var中删除反斜杠? [英] How to remove backslash escaping from a javascript var?

查看:99
本文介绍了如何从javascript var中删除反斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个var

var x = "<div class=\\\"abcdef\\\">";

哪个是

<div class=\"abcdef\">

但是我需要

<div class="abcdef">

我如何unes​​cape这个var可以删除所有转义的字符?

How can I "unescape" this var to remove all escaping characters?

推荐答案

您可以通过正则表达式替换一个反斜杠后跟引号,而 String#replace function:

You can replace a backslash followed by a quote with just a quote via a regular expression and the String#replace function:

var x = "<div class=\\\"abcdef\\\">";
x = x.replace(/\\"/g, '"');
document.body.appendChild(
  document.createTextNode("After: " + x)
);

请注意正则表达式只是一个反斜杠在文字中有两个,因为您必须使用反斜杠在正则表达式文字中转义反斜杠(就像字符串文字中一样)。

Note that the regex just looks for one backslash; there are two in the literal because you have to escape backslashes in regular expression literals with a backslash (just like in a string literal).

在正则表达式的末尾,g 告诉替换在整个字符串(全局)中工作;否则,它只会替换第一场比赛。

The g at the end of the regex tells replace to work throughout the string ("global"); otherwise, it would replace only the first match.

这篇关于如何从javascript var中删除反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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