0

What do I want?

I want to create an object property what capitalizes every word in a string, optional replaces underscores with spaces and/or lowercase the string first. I want to set the options by two parameters:

First parameter true?

Then replace all underscores with whitespace.

Second parameter true?

Then lowercase the complete string first.

What do I have so far working?

replace underscore with space first and then capitalize all words:

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));

FIDDLE

lowercase string first and then capitalize all words:

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));

FIDDLE

What are my questions?

  • This is the first time I'm trying to create an object property with this condition notice. How can I join this two options into my object property function that I only have to set the two parameters?

For example:

//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));
  • What is anyway the name of writing the condition with syntax notation like "?" and ":"?
Dinizworld
  • 394
  • 1
  • 6
  • 16
  • 2
    The `…?…:…` operator is the “conditional operator”. In this case, you should use a few `if` statements to be non-confusing. – Ry- Jun 24 '14 at 17:21
  • 1
    Don't call that thing a property. It's a *method*! – Bergi Jun 24 '14 at 17:27
  • @ Bergi Thanks for this comment, the better i know how to call *things* the easier it is to search for explanations, examples, tutorials etc.. – Dinizworld Jun 24 '14 at 17:31
  • @false alright, than I will use if statements instead of conditional operators. Because I'm curious, isn't it even possible with conditional operators? – Dinizworld Jun 24 '14 at 17:34
  • 1
    @Dinizworld: It is, but you have to add one for every combination (without variables); it’s not pleasant. – Ry- Jun 24 '14 at 17:55

0 Answers0