我有一些JavaScript代码可以将愚蠢的引号转换为contenteditable
中的智能引号。
当您在仅关闭的行的开头添加哑引号时,会出现问题。例如,你得到这个:
”dumb quotes” instead of “dumb quotes”
试用演示:http://jsfiddle.net/7rcF2/
我正在使用的代码:
function replace(a) {
a = a.replace(/(^|[-\u2014\s(\["])'/g, "$1\u2018"); // opening singles
a = a.replace(/'/g, "\u2019"); // closing singles & apostrophes
a = a.replace(/(^|[-\u2014/\[(\u2018\s])"/g, "$1\u201c"); // opening doubles
a = a.replace(/"/g, "\u201d"); // closing doubles
a = a.replace(/--/g, "\u2014"); // em-dashes
return a };
有什么想法吗?谢谢!
P.S。我很喜欢正则表达式......
答案 0 :(得分:7)
试试这个:
var a = '"dumb quotes" instead -- of "dumb quotes", fixed it\'s';
a = a.replace(/'\b/g, "\u2018") // Opening singles
.replace(/\b'/g, "\u2019") // Closing singles
.replace(/"\b/g, "\u201c") // Opening doubles
.replace(/\b"/g, "\u201d") // Closing doubles
.replace(/--/g, "\u2014") // em-dashes
.replace(/\b\u2018\b/g, "'"); // And things like "it's" back to normal.
// Note the missing `;` in these lines. I'm chaining the `.replace()` functions.
输出:
'“dumb quotes” instead — of “dumb quotes”, fixed it's'
基本上,您正在寻找word boundary:\b
<强> Here's an updated fiddle 强>
答案 1 :(得分:1)
如果您希望客户端完成所有操作,可以使用smartquotes.js库将页面上的所有哑引号转换为智能引号。或者,您可以使用the library itself中的函数:
function smartquotesString(str) {
return str
.replace(/'''/g, '\u2034') // triple prime
.replace(/(\W|^)"(\S)/g, '$1\u201c$2') // beginning "
.replace(/(\u201c[^"]*)"([^"]*$|[^\u201c"]*\u201c)/g, '$1\u201d$2') // ending "
.replace(/([^0-9])"/g,'$1\u201d') // remaining " at end of word
.replace(/''/g, '\u2033') // double prime
.replace(/(\W|^)'(\S)/g, '$1\u2018$2') // beginning '
.replace(/([a-z])'([a-z])/ig, '$1\u2019$2') // conjunction's possession
.replace(/((\u2018[^']*)|[a-z])'([^0-9]|$)/ig, '$1\u2019$3') // ending '
.replace(/(\u2018)([0-9]{2}[^\u2019]*)(\u2018([^0-9]|$)|$|\u2019[a-z])/ig, '\u2019$2$3') // abbrev. years like '93
.replace(/(\B|^)\u2018(?=([^\u2019]*\u2019\b)*([^\u2019\u2018]*\W[\u2019\u2018]\b|[^\u2019\u2018]*$))/ig, '$1\u2019') // backwards apostrophe
.replace(/'/g, '\u2032');
};