#1 String Concatenation
var string1 = "Hello"; var string2 = "world"; var concatenatedString = string1 + " " + string2; console.log(concatenatedString);
The above snippet gives you a “Hello world” output. Take note that the space was added after we put an empty space between string1 and string2. Without it, the output would be “Helloworld” – the result of concatenating “Hello” and “world.”
#2 Determine Character Count
Next, we learn how to determine the length of a string. This is easily accomplished by using stringName.length where length is the function that counts each character of the string and numbers each. The first character is 0, the second is 1 and so on. Here is an example.
var string1 = "Hello"; string1.length;
By running the above snippet, you will find the length of the string (the number of characters counted) in the console log. What will you use this for? Take for example, Twitter. Consider how it limits the number of characters you can tweet. That’s right. Determining the character count makes it possible for Twitter to limit tweets to a certain number of characters.
#3 Slicing String Into Parts
We already learned how to connect strings into one (concatenation), now we will learn how to separate a string into parts with slice. It works almost the same as length. Except, slice requires parameters (or user input) to determine the length of the string we want to slice and separate from the main string.
var string1 = "Hello"; string1.slice(0,1);
The output of above’s snippet will give us “H.” Here’s why. Slice requires at least one parameter which is the starting point of the slice. This is the character number where the slicing starts. In our example, I wrote 0 which is “H.” The second parameter is optional, but it determines where to end the slice. I wrote 1 which is at “e” but “e” is not included in the actual slice because the second parameter only determines the ending point of the slice but is not actually included in the slice. Suffice to say, if we do not specify the second parameter, there is no end point and the slice takes the rest of the string from the starting point (first parameter).
#4 Changing Text Case
var string1 = "Hello"; string1.toUpperCase();
By running the snippet above, you will have “HELLO” on your console if you used toUpperCase() or “hello” if you used toLowerCase().