问问题
2485 次
2 回答
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'
基本上,您正在寻找边界一词:\b
于 2013-02-15T08:33:28.467 回答
1
如果您希望一切都在客户端完成,您可以使用smartquotes.js库将页面上的所有哑引号转换为智能引号。或者,您可以使用库本身的正则表达式。
这是旧版本代码的实现:
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');
};
于 2016-09-14T20:30:45.270 回答