Back to another round of Web Basics. In the last one, we learned How to Reverse a String in Javascript. By the way, for those new to my community. Web Basics is a series on essential programming topics every web developer should absolutely know! You can catch the web basics posts on my Instagram. Alright enough intro, let's get going with our lesson 🤓
Here are the 3 methods I'll be covering:
toUpperCase()
slice()
charAt()
toLowerCase()
By the end, you will be able to apply what you learned and solve this basic algorithm challenge:
/** Capitalize a Word
*
* Implement a function that takes a word and
* return the same word with the first letter capitalized
*
* capitalize('aWESOME')
* Output: 'Awesome'
*
*/
You ready! Great, let's get started! 💪
Web Basics: toUpperCase()
This method is used to convert all the letters in a string to uppercase. It doesn’t change the original string. Instead, it will return a new modified string 🔅
const name = 'samantha';
const result = name.toUpperCase();
console.log(result);
// 'SAMANTHA'
Web Basics Examples: toUpperCase()
Ex 1:
Let’s take a look at some use cases with this method. As you can see, it doesn’t affect the original string. If you have a string with numbers, there’s no uppercase of it, so that doesn’t change.
const text = 'Web Basics 101';
const upper = text.toUpperCase();
text; // 'Web Basics 101'
upper; // 'WEB BASICS 101'
Ex 2:
One thing to note. This method is only applicable for strings. If you try to pass in other data types (such as null
, undefined
, or number
), it will throw an error. You will get a TypeError
. So make sure you check the type before passing it into this function, otherwise, your app will crash.
(null).toUpperCase(); // TypeError
(undefined).toUpperCase(); // TypeError
(['hi']).toUpperCase(); // TypeError
(45).toUpperCase(); // TypeError
Web Basics: charAt()
This method returns the character at the specified index of a string.
const name = 'samantha';
const result = name.charAt(0);
console.log(result);
// 's'
Web Basics Examples: charAt()
Ex 1:
The default is 0. That means it returns the first letter. Remember, array in JavaScript are 0-indexed. So the first letter starts at index 0.
const text = 'Web Basics';
text.charAt(); // default is 0
// 'W'
text.charAt(text.length - 1); // get the last letter
// 's'
text.charAt(1000); // out of range index
// ''
Ex 2:
What happens if you're a smarty-pants and want to pass something that isn't a number 😝 Well if you try to do that, the default will just take over and you will get the first letter.
// Everything else will be the default (0)
'hi'.charAt(undefined); // 'h'
'hi'.charAt(null); // 'h'
'hi'.charAt(false); // 'h'
'hi'.charAt('W'); // 'h'
Difference between charAt()
and []
notation
If you have a bit more JavaScript experience, you might see others using the bracket notation to access the string.
const name = 'Samantha';
name.charAt(2); // 'm'
name[2]; // 'm'
They give you the same result, so what's the difference. Well, it all comes down to browser support. charAt
was introduced in the first ECMAScript 1, so it's supported by all browsers 🤩. Whereas the bracket notation was introduced in ECMAScript 5. So bracket notation method doesn't work in Internet Explorer 7 and below. Something definitely to keep in mind, especially when you're working with client projects that require older browser support.
Web Basics: slice()
This method extracts a section of a string and returns the extracted part as a new string 🍏 One more reminder that JavaScript is 0-index. So the first character has a 0 position, and the second character has a 1-position 👍
This method accepts 2 parameters: start and end
start this is where you pass in the starting index to extract. If you don’t pass in anything, the default is 0 (or the first character).
end this is where you pass the index before which to end the extraction. Note, the character at this index will not be included. If you don’t pass in anything, slice()
will select all characters from the starting point to the end.
const name = 'samantha';
const sliced = name.slice(0,3);
console.log(sliced); // 'sam'
console.log(name); // 'samantha'
Web Basics Examples: slice()
Ex 1:
slice()
is a great way to clone or copy a string. You can either pass in 0 or just let the default kick in with no arguments. If you want the last letter, you can simply pass -1.
'Web Basics'.slice(0); // clone the string
// 'Web Basics'
'Web Basics'.slice(); // default is 0
// 'Web Basics'
'Web Basics'.slice(-1); // get the last letter
// 's'
Ex 2:
You can play around the starting and ending value with either a positive or negative number to extract the part of the string you want.
'Web Basics'.slice(4, 7); // 'Bas'
'Web Basics'.slice(-6, -3); // 'Bas'
'Web Basics'.slice(4, -3); // 'Bas'
Ex 3: Out of range starting index
If you pass a starting value that is greater than the length, an empty string will be returned. On the contrary, if you pass in a negative starting value that exceeds the length, it will simply return the entire string.
'Web Basics'.slice(1000); // ''
'Web Basics'.slice(-1000); // 'Web Basics'
Web Basics: toLowerCase()
This method is used to convert all the letters in a string to lowercase. It doesn’t change the original string. Instead, it will return a new modified string. Essentially the opposite of toUpperCase()
.
const name = 'SaMaNthA';
const result = name.toLowerCase();
console.log(result);
// 'samantha'
Web Basics Examples: toLowerCase()
Ex 1:
const original = 'WeB BasIcS 102';
const lower = original.toLowerCase();
console.log(original); // 'WeB BasIcS 102'
console.log(lower); // 'web basics 102'
Ex 2:
Just like toUpperCase()
, this method is only applicable for strings. If you try to pass in other data types (such as null
, undefined
, or number
), it will throw an error. You will get a TypeError
. So make sure you check the type before passing it into this function, otherwise, your app will crash.
(null).toLowerCase(); // TypeError
(undefined).toLowerCase(); // TypeError
(['hey']).toLowerCase(); // TypeError
(75).toLowerCase(); // TypeError
Algorithm Challenge
Alright, now let's piece everything together! Here's your algorithm challenge! You should be able to solve it with the built-in functions we went through together 💪
/** Capitalize a Word
*
* Implement a function that takes a word and
* return the same word with the first letter capitalized
*
* capitalize('hello')
* Output: 'Hello'
*
* capitalize('GREAT')
* Output: 'Great'
*
* capitalize('aWESOME')
* Output: 'Awesome'
*
*/
How did you do, did you manage to solve it? I'm not going to put the solution in this blog post. But I will provide a link to my solution, which you can use to compare with mine. Remember there are multiple ways to solve this challenge. There is no right way or wrong way. That's the great thing about programming, you can achieve the same result with a multitude of ways. Of course, some ways are more performant than others. But you know what, as code newbies, let's just focus on being able to solve it. That's the first step. And you can always refactor as you gain more confidence and learn more ways of problem-solving.
Resources
- MDN Web Docs: toUpperCase
- w3schools: toUpperCase
- MDN Web Docs: charAt
- w3schools: charAt
- MDN Web Docs: slice
- w3schools: slice
- MDN Web Docs: toLowerCase
- w3schools: toLowerCase
- Stack Overflow: string.charAt(x) or string[x]
Thanks for reading ❤
Say Hello! Instagram | Twitter | Facebook | Medium | Blog
Top comments (26)
I have a function exactly do that. (I use this function for 3 years. I just changed for new ES standards)
In this example, this function firstly takes a string.
After that, the whole string will be lowercase.
After that, the string will be split with empty spaces. (Ex: I HAVE NO IDEA)
Now, we have words array. I use the map method to manipulate the array.
We'll take the first letter of the word. This letter will be uppercase. The others will be lowercase.
If you know how the substring method works, you won't be confused.
And the last one, we'll concatenate the words to create our new string. That's all.
Might be more performant since you have to loop the array anyway
You can just map on the string :v
But no, it's most likely not going to be performant (even like this), because it involves indexing into every character instead of handing the underlying native string to the native method.
Worse yet,
.split('')
and such don't play well with composite Unicode graphemes.Woo, I love this solution! Nice use to the falsy value to check the first character (cause 0 is false). Thanks for sharing 💯
You can omit the second argument in
substring
,substr
andslice
to get the rest of the string until the end.You can also use
charAt(0)
or even.charAt()
to get the first char instead of a slicing method.Nice use to map! And awesome explanation with it! Thanks for sharing 🤓
here's my take on it with ES7
a little cleaner
I didn't think of it that way. I like it!
One-liner solutions are most of the time my favs too! 😜
TextDecoder
solution:Many checks are missing. This is intentional, because we are going to pretend that this is performant.
String.prototype.replace(regex, fn)
solution:If you only want the first word capitalized:
This is probably the best multi-word solution.
I totally forgot about
\b
, it is excellent.I totally emulated it with
/(?:^|\s)\w/
, since capitalizing the whitespace doesn't do anything, but this is just so much better!Does the
i
flag improve performance and not harm it though?I'd potentially hoist the regex and callback constructions out of the function, although that may be crazy to do.
Hi, the
i
doesn't does anything in this case, it is my mania of writing it always. The mdn's docu says this about \w:So \w is case insesitive already.
OH NO
:'(
That was expected, which result do you wanted?
Try my honestly unironically inferior regex and see:
regex ahhhh 😅 I need to get better at that cause I know how powerful it is 😆
Not as fancy as other solutions but I believe this works.
No need to always be fancy. This works perfectly! Great 👍
Awesome guide!
This is one situation where I REALLY wish JS would take after Python.
I'm not familiar with Python -- is it more concise?
Python has an awesome title() method that will capitalize the first letter of every word in a string while lower casing the others.
Another great post as usual. 👍
Thanks! 😄