有一些特殊的方法来引用引号(单引号和双引号),如何在JavaScript或Jquery中转义或无论如何处理它们。
我目前的努力是
text.replace(/(['"])/g, "\\$1");
但这只会有助于处理'
和"
在某些情况下,用户使用’s
和“Ang”
1. Peter’s book
2. Mike's book
1. "Comment"
2. “Post”
答案 0 :(得分:1)
有一个wide range of quotes。您可以将它们添加到正则表达式的character class,如下所示。直接:
$("button").click(function() {
$("pre").text(function(_, text) {
return text.replace(/(['"‘’“”`´])/g, "\\$1");
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>
- 'straight single'
- "straight double"
- ‘opening/closing single’
- “opening/closing double”
- `Grave`
- ´Grave´
</pre>
<button>Click to escape</button>
&#13;
或逃脱:
$("button").click(function() {
$("pre").text(function(_, text) {
return text.replace(/(['"\u2018\u2019\u201C\u201D`´])/g, "\\$1");
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>
- 'straight single'
- "straight double"
- ‘opening/closing single’
- “opening/closing double”
- `Grave`
- ´Grave´
</pre>
<button>Click to escape</button>
&#13;