我想要什么?
我想创建一个对象属性,它将字符串中的每个单词大写,可选用空格替换下划线和/或首先将字符串小写。我想通过两个参数设置选项:
第一个参数为真?
然后用空格替换所有下划线。
第二个参数为真?
然后首先将完整的字符串小写。
到目前为止我有什么工作?
先用空格替换下划线,然后将所有单词大写:
String.prototype.capitalize = function(underscore){
return (underscore ? this.replace(/\_/g, " ") : this).replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
}
var strUnderscoreFalse = "javaSCrIPT replace_First_underderscore with whitespace_false";
//replace underscore first = false
console.log(strUnderscoreFalse.capitalize());
var strUnderscoreTrue = "javaSCrIPT replace_First_underderscore with whitespace_true";
//replace underscore first = true
console.log(strUnderscoreTrue.capitalize(true));
先小写字符串,然后大写所有单词:
String.prototype.capitalize = function(lower){
return (lower ? this.toLowerCase() : this).replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
}
var strLcaseFalse = "javaSCrIPT lowercase First false";
//lowercase first = false
console.log(strLcaseFalse.capitalize());
var strLcaseTrue = "javaSCrIPT lowercase First true";
//lowercase first = true
console.log(strLcaseTrue.capitalize(true));
我有什么问题?
- 这是我第一次尝试使用此条件通知创建对象属性。如何将这两个选项加入到我只需设置两个参数的对象属性函数中?
例如:
//replace underscore first = true and lowercase first = true
console.log(str.capitalize(true , true));
//replace underscore first = false and lowercase first = true
console.log(str.capitalize(false , true));
- 无论如何,用“?”之类的语法符号编写条件的名称是什么?和“:”?