Cara menggunakan javascript capitalize first letter

Cara menggunakan javascript capitalize first letter
In JavaScript capitalize first letter using charAt (), slice () or toUpperCase () methods. These JavaScript methods can capitalize the first letter of a JavaScript string or the first letter of each word in a JS string.

In this review, you will master first letter capitalization in JS with the above methods. Keep reading to see which method fits your current coding project.

Contents

  • How To Capitalize First Letter in JavaScript: Methods To Implement
  • JavaScript Strings: How To Capitalize First Letter of String
    • – Using toUpperCase () Method Alone
    • – Syntax
    • – Code Example: Capitalize Full Sentence
  • How To Uppercase the First Letter Only Using The toUpperCase() Method
    • – Code Example
  • JavaScript Capitalize First Letter: Combining the Three Methods
    • – charAt() Method
    • – Syntax
    • – Code Example
    • – The Slice() Method
    • – Syntax
    • – Code Example
    • – The Three Functions Code Example
  • JavaScript Uppercase First Letter: Capitalize Each First Letter in a JS String
    • – Split the String Into Separate Words
    • – Iterate Through the Array and Uppercase Every First Character
    • – Recombine the Array Into a Single String
  • Conclusion

How To Capitalize First Letter in JavaScript: Methods To Implement

The different methods mentioned above offer flexibility regarding letter capitalization in JavaScript. You can turn only the first letter of a string into a capital letter. For example:

“this is my car” → “This is my car.”

Also, you can use these methods in JavaScript to uppercase first letter of each word in a string. For instance:

“this is my car” → “This Is My Car.”

It is that simple. However, achieving stellar results requires a deeper understanding of how each method works individually or with similar functions.

In this section of our article, we are going to be looking into various ways of capitalizing letters in JavaScript.

JavaScript Strings: How To Capitalize First Letter of String

You can use the toUpperCase () method alone or combine it with the slice () method and charAt () methods to change into uppercase the first letter of a string in JavaScript.

– Using toUpperCase () Method Alone

The toUpperCase () method will capitalize string JavaScript has without changing the contents of the string. However, the technique turns the content of the entire string into capital letters.

Remember, strings in JavaScript are immutable. So, after invoking the toUpperCase method, the results will be two strings within the code memory. The resulting strings are the converted string and the original string.

– Syntax

– Code Example: Capitalize Full Sentence

const str = ‘How are you!’;
console.log(str.toUpperCase());  // expected output: HOW ARE YOU!

This method does not take any parameters. Also, capital letters will remain unchanged. In the example above, H is unchanged.

Additionally, the method does not affect special characters, like “!” at the end of the string. Similarly, digits remain unchanged. In the new string, these characters remain in the exact location as they were in the original string.

How To Uppercase the First Letter Only Using The toUpperCase() Method

It takes three steps to uppercase only a single letter of a JavaScript string:

  1. Pinpoint the first letter and invoke the toUpperCase() method on that first letter
  2. Cut off that first letter from the rest of the string to generate a new string minus the first character.
  3. Join the two strings.

Here, use the index of the string’s first character with substring notation [0] and then capitalize by applying toUpperCase(). In Js, counting starts from zero, meaning that the first position of an array is zero; this also applies to a string.

– Code Example

const publication = “freeCodeCamp”;

To remove the letter (f) from freeCodeCamp, invoke publication[0] as shown in the code example below:

const publication = “freeCodeCamp”;
publication[0].toUpperCase();

Alternatively, you can use the substring() method for the second portion to generate a string consisting of all characters except the first.

When you run the code, it will return a capital F rather than a small f. If you want to get the entire word back, run the code below:

const publication = “freeCodeCamp”;
publication[0].toUpperCase() + publication.substring(1);

This action concatenates the capital “F” with “reeCodeCamp,” giving rise to the word “FreeCodeCamp.” It uses the ‘+’ operator to combine the two strings.

JavaScript Capitalize First Letter: Combining the Three Methods

You can combine the three methods in JavaScript to uppercase first letter of a JS string. But first, let’s define the remaining two methods –  slice () and charAt ().

– charAt() Method

The JS charAt() methods returns a character at a specified position/index in a string.

– Syntax

An index is an integer between “0” and stringName.length -1. If no index is provided or the index cannot be converted to the integer, the default value is ‘0’; thus, returning the first character of str.

– Code Example

const str = ‘cow dung’;
const str2 = str.charAt(0);
console.log(str2);
//Output: c

This code example displays a character at the first position of a string. Remember, characters are indexed from left to right in a string, and the first character index is usually 0 while the last character is stringName.length – 1.

– The Slice() Method

The slice() method in JavaScript extracts a portion of a string and returns the extracted portion in a new string without changing the original string. Typically,  the slice() function slices a string from a specified between two specified points (start and endpoints). The start and endpoints represent the index items within that array.

– Syntax

The start point is an optional, zero-based index and indicates where to start the extraction process. You can use a negative index, indicating an offset from the end of the sequence. When the start is undefined, the slice will begin from index ‘0’. By contrast, if the start is greater than the index range of the sequence, it returns an empty array.

Similarly, the end is optional and is a zero-based index before the point of the end of extraction. Slice () function extracts, up to but not including, end. For instance, slice(1, 5) extracts elements indexed 1,2,3 and 4.

You can use a negative index, too, indicating an offset from the end of the sequence. When you omit end, slice () extracts through the end of the sequence.

– Code Example

let text = “cow dung!”;
let result = text.slice(0,5);
//Output: cow d

– The Three Functions Code Example

const str = ‘cowdung’;
const str2 = str.charAt(0).toUpperCase() + str.slice(1);
console.log(str2);
//Output: Cowdung

The code’s output above shows how easy it is to combine the three methods to uppercase the first letter of a JavaScript string.

When you want to capitalize first letter of string JavaScript lets you use the above-mentioned methods. However, it is slightly different when you want to capitalize the first letters of each word in a JavaScript string. Check out the code example:

const str = ‘welcome friend, how have you been?’;

Here is how to go about it and capitalize each letter of each word yourself:

– Split the String Into Separate Words

It is easier to manipulate each word when you split the string into an array of words, and you can use the split() method to do that. This method takes a string object and splits it according to the characters provided. In this instance, pass the empty space character(‘’) as the value to perform the split.

This action returns an array of all the words in the string together with their special characters and digits. That implies there will be an entry in the array for every portion of the string that is separated by a space character.

This how the code will appear:

const strToArr = str.split(‘ ‘);
console.log(strToArr);
// expected output: [“welcome”, “friend,”, how”, “have”, “you”, “been?”]

Most of the tokens are words; however, the comma after “friend” and a question mark after “been” are considered as part of the word. The reason for this is we command split() to separate values according to spaces in between the words.

– Iterate Through the Array and Uppercase Every First Character

Loop through the array and work with each string. Like in the previous section, take the first character of every single string using the first index ([0]) and then combine them with the remainder of the string obtained from the substring() method.

Let’s view a coding example of how we did this:

const allFirstToUC = strToArr.map(word => word[0].toUpperCase() + word.substring(1));
console.log(allFirstToUC);
// expected output: [“Welcome”, “Friend,”, How”, “Have”, “You”, “Been?”]

This is still an array, not a string; you must combine the words to form a sentence.

– Recombine the Array Into a Single String

In this step, you will put the arrays of substrings back together and re-insert the space characters that the split() method removed. To put the words together, JavaScript offers the method join(). The join() method can return an array as a string as it takes a separator as an argument. Note that you can specify what to add between the words.

The function takes a character to interject into the array of substrings and uses the same character to combine the array elements back into a single string. To get the initial sentence structure, you will need to pass in the empty space character as a parameter, join(‘’).

Here is an example that illustrates this:

const newStr = allFirstToUC.join(‘ ‘)
console.log(newStr);
// expected output: Welcome Friend, How Have You Been?

See, all the first letters of each word are capitalized in the entire string.

Note that there are different methods of iterating through an array. In our code example, we have used the map() method.

Conclusion

This uppercase JavaScript tutorial has taught you the following:

  • How to split a string into words and how to join back the words into a string
  • Using the toUpperCase() method alone to capitalize the first letters in a js string
  • Combining toUpperCase(), Slice() And CharAt() Methods to capitalize letters in JavaScript
  • Using the substring notation [0]) to locate the first letter of a string
  • To capitalize each word in a string, split the words, iterate and then recombine using join()

Cara menggunakan javascript capitalize first letter
This article offers you different methods to use JavaScript to uppercase the first letter of a string or each word in a string. Indeed, it provides more than one method to achieve that. With this article, you should easily manipulate strings in JavaScript.

  • Author
  • Recent Posts

Cara menggunakan javascript capitalize first letter

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Cara menggunakan javascript capitalize first letter