2016-10-18 36 views
1

我有一個函數可以大寫句子。但它不能夠利用的名字,如,javascript中的名稱大寫

D'agostino, Fred 
D'agostino, Ralph B. 
D'allonnes, C. Revault 
D'amanda, Christopher 

我期待:

D'Agostino, Fred 
D'Agostino, Ralph B. 
D'Allonnes, C. Revault 
D'Amanda, Christopher 

功能

getCapitalized(str){ 
    var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i; 
    return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function (match, index, title) { 
     if (index > 0 && index + match.length !== title.length && 
     match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" && 
     (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') && 
     (title.charAt(index + match.length) !== "'" || title.charAt(index - 1) === "'") && 
     title.charAt(index - 1).search(/[^\s-]/) < 0) { 
     return match.toLowerCase(); 
     } 
     if (match.substr(1).search(/[A-Z]|\../) > -1) { 
     return match; 
     } 
     return match.charAt(0).toUpperCase() + match.substr(1); 
    }); 
    } 

任何人可以幫我找出這個問題?我曾嘗試使用(title.charAt(index + match.length) !== "'" || title.charAt(index - 1) === "'"),但它沒有幫助。

+0

不是你測試''''的代碼只適用於匹配'smallWords'的東西嗎? – nnnnnn

+0

哦,我現在看到它!謝謝@nnnnnn –

+0

@nnnnnn你有這方面的最佳解決方案嗎? –

回答

3

我不知道所有你需要照顧的使用情況,但對於你問的問題,你可以使用正則表達式,以查找單詞邊界:

function capitalizeName(name) { 
 
    return name.replace(/\b(\w)/g, s => s.toUpperCase()); 
 
} 
 

 
console.log(capitalizeName(`D'agostino, Fred`)); 
 
console.log(capitalizeName(`D'agostino, Ralph B.`)); 
 
console.log(capitalizeName(`D'allonnes, C. Revault`)); 
 
console.log(capitalizeName(`D'amanda, Christopher`));