2017-05-04 60 views
0

我使用此常用功能將大部分列表項目轉換爲標題大小寫,沒有問題。我發現了一個需要改進的地方,當中間有一條短線或斜線時,我希望下一個字母大寫。在短劃線或斜線後將字符串轉換爲標題大小寫

例如西班牙裔/拉丁裔應該是西班牙裔/拉丁裔。基本上大寫時,第一個字母或一個符號或一個空間。

當前代碼:

function toTitleCase(str) { 
    return str.toLowerCase().replace(/(?:^|\s)\w/g, function (match) { 
     return match.toUpperCase(); 
    }); 
} 

回答

2

只要改變你的空白\s捕獲,是一類的人物是空白,連字符或斜槓[\s-/](以及其他任何你想要的)

function toTitleCase(str) { 
 
    return str.toLowerCase().replace(/(?:^|[\s-/])\w/g, function (match) { 
 
     return match.toUpperCase(); 
 
    }); 
 
} 
 

 
console.log(toTitleCase("test here")); 
 
console.log(toTitleCase("test/here")); 
 
console.log(toTitleCase("test-here"));

1

只需添加或正則表達式條件/(?:^|\s|\/|\-)\w/g

function toTitleCase(str) { 
 
    return str.toLowerCase().replace(/(?:^|\s|\/|\-)\w/g, function (match) { 
 
     return match.toUpperCase(); 
 
    }); 
 
} 
 

 

 
console.log(toTitleCase('His/her new text-book'))

相關問題