字符串首字母大写函数扩展
String.prototype.firstUpperCase= function () {
return this.split(' ').map(function(value, index) {
let arr = value.split('');
let val = value[0].toUpperCase() + value.slice(1);
return val;
}).join(' ');
};
字符串首字母大写,同时加入第二个参数,包含需要小写的条件。
例子:titleCase('a clash of KINGS', 'a an the of') //return: 'A Clash of Kings' 首字母的首个单词一定要大写
titleCase('THE WIND IN THE WILLOWS', 'The In') //return: 'The Wind in the Willows' 同上
titleCase('the quick brown fox') //return: 'The Quick Brown Fox' 同上
方法一:
String.prototype.titleCase = function(minorWords) {
let minor = minorWords === undefined ? [] : minorWords.toLowerCase().split(' ');
return this.toLowerCase().split(' ').map(function(val, index) {
if (val !== '' && (index === 0 || minor.indexOf(val) === -1)) {
val = val[0].toUpperCase() + val.slice(1);
}
return val;
}).join(' ');
}
方法二:
String.prototype.titleCase = function(minorWords) {
let minor = minorWords === undefined ? '' : minorWords.toLowerCase();
if (this === '') return '';
return this.toLowerCase().split(' ').map(function(value, index) {
return value[0].toUpperCase() + value.slice(1);
}).map(function(val, index) {
minor.split(' ').forEach(function(value) {
if (val.toLowerCase() === value && index > 0) val = val.toLowerCase();
})
return val;
}).join(' ');
}