Algorithm Scripting lesson: Title case a sentence

I’m trying to capitalise the first letter of every word in a sentence using JS RegEx.
My code looks like this:

function titleCase(str) {

  let regex = /^(A-Z{1})(a-z*)(\s)\1\2\3/ig;

  str.match(regex);

  return str;

}

I don’t see where I’m going wrong.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

In the future, it’s easier if you use the “Get Help” button in the challenge.

.match() doesn’t change the string. .match() just checks for whether a string matches a regular expression.

1 Like

Hi @ambareenk321!

Welcome to the forum!

So, I would first look at the test cases provided for you.

Test cases:
titleCase("I'm a little tea pot") should return I'm A Little Tea Pot .
titleCase("sHoRt AnD sToUt") should return Short And Stout
titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") should return Here Is My Handle Here Is My Spout

You should notice that the str could have a mixture of upper and lower case letters.

So it would be easier to work with if you converted everything to one casing.
Then you can go through each word and uppercase only the first letter of each word.

I would dig around mdn docs to find some helpful string methods to help solve this challenge.

1 Like

Yes, I managed to solve it using string methods! I was just wondering why my regex wouldn’t work. I thought my regex does represent the first letter as capital and then the rest as lowercase but I guess I just went wrong somewhere.
Thanks for your help!

Like @ArielLeslie mentioned the match method only looks for a match to the regex.

You weren’t actually changing anything.

1 Like

Ahh I see, thank you!!

Hi @ambareenk321 ,

As others have already pointed out, match method will only return an array with the string it matched.

Meanwhile, I was trying to analyse your regex to see what you were trying to match and probably why it returned null:

To check for A-Z or a-z, they would need to be inside square parenthesis [ ] (shorthand could be used instead \w)
Also, when \1\2\3… is used, it basically means that one is checking for the exact same word to repeat. for example: /(\w*)(\s)\1/ will match “test test” and not “test nomatch”.

Hope it helps.

1 Like