0

I am trying to capitalize the first word of a string

function titleCase(str) {
  var newStr = str.split(" ");
  //TeSt 10 array newStr

  for (var i = 0; i < str.length; i++) {
    //
    (newStr[i][0].replace(new RegExp("[a-z]"), new RegExp("[A-Z]")))
  }

}

titleCase("I´m a little tea pot")

I am very confused about Regex so the code I know is wrong but I´d like to know if it's possible to do it as closely similarly like this. So basically once the first letter of each word has been located (newStr[i][0]) I want to .replace(the noncaps to caps).

I know the RegExp is probably very wrong, but, could something like this work? Combining replace and instead of putting the literal string you want to replace (because that is already done in newStr[i][0]) doing it with Regex

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
J. Cake
  • 331
  • 4
  • 19

3 Answers3

2

You could match the first character and use the replacer function:

 newStr[i] = newStr[i].replace(/[a-z]/, it => it.toUpperCase());

But why don't you just do:

 newStr[i] = newStr[i][0].toUpperCase() + newStr[i].slice(1);

You could also just use a Regex to replace all occurences:

"test test".replace(/(^| )[a-z]/g, it => it.toUpperCase()))

Explanation:

(^| ) -> is at the beginning of the string (^) or (|) is after a whitespace ( )

[a-z] -> is a letter

/g -> apply to all found characters

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

The replace function has two parameters: pattern and replacement. Pattern is what to search for, and can be either a fixed string, or a regular expression. The replacement can be either a string (optionally with group placeholders that can be copied as-is into the replacement), or a function (that is much more flexible in what replacement it can produce). It cannot be a regular expression, which is the reason your code can't work.

A simple copy-paste cannot turn a lowercase letter into an uppercase, so you have to go with a replacer function:

newStr[i] = newStr[i].replace(new RegExp("[a-z]"),
    function(match) { return match.toUpperCase(); }
)

However, you can avoid even splitting if you just let the regular expression look for the word breaks: \b\w will look for word characters (a-z, A-Z, 0-9 or _) that follow a word boundary (i.e. come either at the start of the string, or after a non-word character). It does not matter that you also look for digits and underscores, as they will not change by uppercasing. You can also use the new function syntax, and the regexp literal syntax, to shorten the code:

str = str.replace(/\b\w/, alnum => alnum.toUpperCase());
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

Even more shortly:

console.log(
  "I´m a little tea pot".replace(/\b\w/g, word => word.toUpperCase())
);

Or, with a function:

function titleCase(str) {
  return str.replace(/\b\w/g, word => word.toUpperCase());
}
titleCase("I´m a little tea pot")
MarcoS
  • 17,323
  • 24
  • 96
  • 174