Introduction

Just how common it is to use strings in programming, is it common to process them. For instance one may want to find the number of character in a string, or slice a part of it, replace certain occurences in it from a given substring, convert the string to uppercase characters and much more.

JavaScript provides developers with a solid handful of string methods to aid in processing strings for different purposes. In this chapter we will go over some of the most useful of these and how exactly to use them. We'll solve common problems using the methods and test your skills by assigning you various tasks in the way.

So why are we waiting here?

Properties

length

The length property gives the number of characters in a string. which can also be refered to as the length of the string.

It is used more than frequently with strings.

var str1 = "Apples";
console.log(str1.length); // returns 6

var str2 = "Apples are fruits";
console.log(str2.length); // returns 17
In this example try counting the number of characters yourself. The answer should work out the same. Just remember one thing that spaces are also counted since they are also part of the string.

You are given two strings a and b. Your task is to determine which string is the longer of the two, or that both are equal in length. Likewise output:

  1. "A" is a if longer than b
  2. "B" if b is longer than a
  3. "Equal" if both are of the same length.

Since we need to check for the length of the given strings a and b, we need to use their length properties. The rest is then just the game of three conditionals.

if (a.length > b.length) console.log("A");
else if (b.length > a.length) console.log("B");
else console.log("Equal");

Methods

toLowerCase()

The toLowerCase() method converts a string to lowercase characters.

var str = "LOWERCASE ME!";
console.log(str.toLowerCase()); // lowercase me!
Remember that toLowerCase(), and all string methods that modify the main string, return new strings. This means that in the above example if you log str after the call of the methods, it will show up the same as before.
var str = "LOWERCASE ME!";
console.log(str.toLowerCase()); // lowercase me!
console.log(str); // "LOWERCASE ME!";
This is because strings are an immutable data type as highlighted in the previous Strings Basic Concepts chapter.

toUpperCase()

Similarly, toUpperCase() converts a string to uppercase characters.

var str = "uppercase me!";
console.log(str.toUpperCase()); // UPPERCASE ME!

charAt()

Now it's your time to guess! Think what will the method do. ("char" is for character).

The charAt() method returns the character at a specified position (a better term would be index).

Always remember one thing in JavaScript programming - indexes start at zero.
var str1 = "Let's test the method charAt()!";

console.log(str1.charAt(0)); // L
console.log(str1.charAt(2)); // t
console.log(str1.charAt(3)); // '
console.log(str1.charAt(str1.length - 1)); // !

indexOf()

The indexOf() method is used to find the index of a given string inside the main string (on which the method is called). If the given string is not found -1 is returned.

An instance of where can this method be used is in finding @ characters in email addresses. If the index of @ isn't -1 the the email address is passed for a next check.

var email1 = "[email protected]"; // valid email address;
console.log(email1.indexOf("@")); // returns 6

var email2 = "example.com" // invalid email address;
console.log(email2.indexOf("@")); // returns -1
Having known that @ exists in an email can't be the only thing determing that the email address is correctly written. A period also needs to be checked just for example.
Therefore an email address has to match a given pattern rather than have a given character and this could be accomplished using regular expressions which you will learn in the next chapter.

Emily wants to confirm whether the variable food contains the word "pizza" or not, but she has been facing an issue for a while now.

The issue is that the word "pizza" can be in any casing - it can be there as "PIZZA", "Pizza", "piZza" and so on. Even these cases are acceptable matches of the word "pizza" - it's just that they are not in lowercase!

Can you help Emily solve this problem without needing to check for all 32 casings manually?

Definitely we need the method indexOf() to search for the fixed-length value "pizza" in food, but not directly. First we need to convert food to lowercase to ensure everything is unified under one casing (it could've been uppercase as well, but generally lowercases are preferred).

Once this has been done, the problem is just the matter of seconds to be ultimately solved using food.indexOf("pizza")

// unification of casing
food = food.toLowerCase();
// confirming whether the word "pizza" is there
console.log(food.indexOf("pizza") !== -1);

lastIndexOf()

The lastIndexOf() method is same as indexOf() except that is starts searching from the right. If the given string is not found -1 is returned.

var str1 = "First Come First Serve";

console.log(str1.indexOf("First")); // returns 0
console.log(str1.lastIndexOf("First")); // returns 11
As we said earlier that the names are self-descriptive, try to relate the purpose of the function with its name.

How can you use the method lastIndexOf(), together with indexOf(), to make sure that a string str contains at least 2 occurences of a substring substr?

Write a piece of code to implement this check and then output true if the requirement is met, or else false.

If str.indexOf(substr) returns -1 we know that there is nothing further to search for and likewise end. However if this is not the case, then we go one step further and check if str.lastIndexOf(substr) is equal to the previous result (from indexOf()). If it isn't, we conclude that there are at least 2 occurences of substr.

// str is the main string
// substr is the string to search for
var i = str.indexOf(substr);
if (i !== -1 &&  i !== str.lastIndexOf(substr)) console.log(true);
else console.log(false);

replace()

The replace() method replaces a substring within the main string and returns the final string. It accepts two parameters - the string/pattern to search for and the string to replace it with.

The substring is usually a part, or parts, of the main string but can also be the complete main string as in the example below.

var str1 = "Replace me";
var repStr = str1.replace("Replace me", "I am replaced!");
// The first argument is the string/pattern to search for
// The second argument is the replacing string

console.log(repStr); // I am replaced!

slice()

The slice() method can come handy when one wants to slice i.e extract portions out of a main string. It takes two arguments - the index where to start slicing (inclusive) and second, the index where to end it (exclusive).

The second argument is optional and will default to the length of the string i.e the slice will be performed from the starting index to the end of the string..

var str1 = "Slice of a pizza";
console.log(str1.slice(0, 2)); // Sl;
console.log(str1.slice(0,4)); // Slic;

// The second argument is optional. Omitting it would slice the rest of the string
console.log(str1.slice(11)); // pizza;
Iterating over the idea once again: all these methods only alter a copy of the original string and return it - the original string can't be changed at all. This is owing to the immutability of strings in JavaScript.

split()

The method split() serves to split up a string into an array of substrings, at a given delimiter (a.k.a. a separator).

In simple words, the string is broken apart at every place where the given separator occurs. For example, breaking "1-2-3" at every hyphen - would result in producing three substrings: "1", "2" and "3".

This separator (or delimiter) goes as an argument to split(). If it's omitted, the method merely returns an array with only one element i.e the original string.

Consider the example below where we split a string items, at every comma , character:

var items = "Apples,Grapes,Mangoes";

var itemsList = items.split(",");
console.log(itemsList); // ["Apples", "Grapes", "Mangoes"]

Notice how the splitting produces an array of the individual substrings.

Following we split a string msg into an array of characters, using the delimiter "":

var msg = "Hello";

var msgChars = msg.split("");
console.log(msgChars); // ["H", "e", "l", "l", "o"]
Remember one thing that whatever separator you choose for split(), it will be exactly matched in the main string. For example, in the following code, ", " will be exactly matched in the splitting - if it isn't found then simply no splitting will occur:
var str = "123, 50, 70,80";
str.split(", "); // ["123", "50", "70,80"]

Split the string str shown below at each space character and save the result back again in str.

var str = "10 20 1 1 0";

The delimiter is clearly mentioned in the question itself: " " - a space character. Thereby following is the solution:

var str = "10 20 1 1 0";
str = str.split(" ");

In the end

Strings are vital to programming and so are properties and methods to strings. Without the methods, especially, strings can only be written and as-it-is displayed - no functionality and no fun!

Now it may take you sometime to remember the method names i.e where to capitalize, the types of their arguments, how many argument can they can accept, return values etc. That sometime can be a lot of time if you don't practice.

Open the console and start experimenting. Notice the key points discussed in the paragraph above like method names, arguments, etc. Try to relate method functionalities with their names. This way you can ensure a solid grip over JavaScript methods discussed above in no more than just a week.

Remember to be patient and experimental!