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.
So why are we waiting here?
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
You are given two strings
b. Your task is to determine which string is the longer of the two, or that both are equal in length. Likewise output:
aif longer than
bis longer than
"Equal"if both are of the same length.
Since we need to check for the length of the given strings
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");
toLowerCase() method converts a string to lowercase characters.
var str = "LOWERCASE ME!"; console.log(str.toLowerCase()); // lowercase me!
toLowerCase(), and all string methods that modify the main string, return new strings. This means that in the above example if you log
strafter 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!";
toUpperCase() converts a string to uppercase characters.
var str = "uppercase me!"; console.log(str.toUpperCase()); // UPPERCASE ME!
Now it's your time to guess! Think what will the method do. ("char" is for character).
charAt() method returns the character at a specified position (a better term would be index).
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() 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
-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
@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" 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
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
// unification of casing food = food.toLowerCase(); // confirming whether the word "pizza" is there console.log(food.indexOf("pizza") !== -1);
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
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
Write a piece of code to implement this check and then output
true if the requirement is met, or else
-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
// 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() 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() 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;
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:
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
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"]
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
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.
Remember to be patient and experimental!