2016-11-23 122 views
1

我想創建一個函數,應該大寫句子中的每個第一個單詞+它也應該大寫縮寫字符。如何大寫縮寫和字符串中的每個第一個單詞?

例如:
a.m.a.一般精神病學檔案 - > A.M.A.普通精神病學檔案

a.m.a.神經病學檔案 - > A.M.A.神經病學檔案

a.m.a.神經病學和精神病學檔案 - > A.M.A.神經病學與精神病學

這裏的檔案是什麼我迄今爲止嘗試:

但至今沒有運氣。

function transform(str) { 
 
    let 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); 
 
    }); 
 
} 
 

 
function showRes(str) { 
 
    document.write(transform(str)); 
 
}
<button onclick="showRes('a.m.a. archives of neurology')">convert</button>

+1

@downvoter - 護理指定有效的理由! – Rayon

+2

按空格拆分字符串,按點分割這些字符串,然後用大寫字母替換index [0]處的每個字母。不需要正則表達式。 – Seth

回答

4

我已經完全重新編寫的功能:

function transform(str) { 
 
    let smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i; 
 
    let words = str.split(' ');  // Get me an array of separate words 
 

 
    words = words.map(function(word, index) { 
 
    if (index > 0 && ~word.search(smallWords)) 
 
     return word;     // If it's a small word, don't change it. 
 
    
 
    if (~word.lastIndexOf('.', 1)) // If it contains periods, it's an abbreviation: Uppercase. 
 
     return word.toUpperCase(); // lastIndexOf to ignore the last character. 
 

 
    // Capitalize the fist letter if it's not a small word or abbreviation. 
 
    return word.charAt(0).toUpperCase() + word.substr(1); 
 
    }); 
 
    
 
    return words.join(' '); 
 
} 
 

 
console.log(transform('a.m.a. archives of neurology')); 
 
console.log(transform('a.m.a. archives of neurology.')); 
 
console.log(transform('a case study. instit. Quar.'));

+1

@WiktorStribiżew:好點。我已經添加了一些東西來忽略尾隨期 – Cerbrus

+1

這是最優雅的答案!像魅力一樣工作!謝謝@Cerbrus –

+0

一個問題:它不適用於案例研究。 instit。 quar.'''仍然是小寫字母 –

相關問題