2013-02-15 50 views
0

我有一些JavaScript代碼將愚蠢的引號轉換爲contenteditable中的智能引號。啞引號轉換爲智能引號Javascript問題

當您在他們僅關閉的行的開頭添加啞引號時,會出現問題。例如,你得到這個:

」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 }; 

任何想法?謝謝!

附:我吸在正則表達式...

回答

6

試試這個:

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

+0

@Cerberus:真棒,它的工作原理。謝謝! – Alex 2013-02-15 08:46:10

+0

這不是一個很好的解決方案。它將事物的撇號轉換爲「它」。 – 2013-12-23 01:58:31

+0

值得注意的是,我使用的動作正則表達式庫,顯然有一個(可能)廢話實現'\ b'。 – 2013-12-23 02:18:33

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'); 
};