Part 3 | A Piece of JavaScript Cake Series
A Beginner’s Guide | Javascript String Methods
In our previous article, we have looked at Primitive, Complex Data Types, and Variables in Javascript. Today, we are going deep dive inside strings and string methods. Our article’s format will be like a cheat sheet. Enough talking, let’s do more coding.
Modern Javascript String Methods
at() Method
Normally, when we try to reach a character in a specific index with charAt by a negative index number, we will get an empty string.
However, with the help of at() method, we can reach a character value in a string by a negative index number. For example:
const exampleString = “Hello”;exampleString.at(-4);
It returns “e” because it’s going backward starting from the zero index which is “H”.
charAt() Method
As we mentioned above we can use charAt() method with positive index numbers for finding specific character values inside a string value.
const exampleString = “Hello”;exampleString.charAt(4);
It returns “o” because it’s going forwards starting from the zero index which is “H”
concat() Method
We can add strings to each other with concat() method. For example:
const firstString = “Hello”;firstString.concat(“ “, “World”); //it returns “Hello World”
We have a first string which is “Hello” then we used concat method, and inside the parentheses, we put an empty string as a space between two words than the second string which is “World”.
startsWith() Method
With the help of this method, we can ask JS if our given string starts with a specific character or not. Js will answer us with a booelan value.
const firstMonth = “January”;firstMonth.startsWith(“J”); // truefirstMonth.startsWith(“K”); //false
endsWith() Method
It has the same functionality as the above method but this time we are asking JS for a given string ending with a specific character.
const firstMonth = “January”;firstMonth.endsWith(“y”); // truefirstMonth.endsWith(“d”); //false
includes() Method
includes method looks for a specific character and returns a boolean value if it exists or not.
const lastDay = “Sunday”;lastDay.includes(“n”); // returns true because “n” existslastDay.includes(“p”); // returns false because “p” does not exists
indexOf() Method
This method is one of the most used string methods in the JS world. It returns the index number of a given character in a string value.
const lastMonth = “December”;lastMonth.indexOf(“r”); //It returns 7lastMonth.indexOf(“e”); // It returns 1
In the last sentence, it returns 1, because when we have duplicate chars in a string it gives us the first one found.
lastIndexOf() Method
As I mentioned above, when we have duplicate characters inside a string, we used indexOf to find the character’s index of where it's used the first time.
With the help of the lastIndexOf, we can find the index where our character was used the last time in a string.
const lastMonth = “December”;lastMonth.lastIndexOf(“e”);
It returns 6 because when we have duplicate chars in a string it gives us the last one found.
match() Method
The match() method matches a string with a regular expression. It converts string values to a regular expression. It returns the starting index number of searched value where it’s found the first time.
- The match() method returns an array with the matches.
- The match() method returns null if no matches are found.
let weather = “The last day was rainy”;weather.match(“ast”); //[‘ast’, index: 5, input: ‘The last day was rainy’, groups: undefined]
or
let weather = “The last day was rainy”;weather.match(“/ast/gi”) //[“ast”]
As its a more detailed topic, you can find the best information from
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
When we got to the Regex part of our series, we will discuss it in more detail.
padStart() Method
padStart method pads the string with desired string to the given length. Padding is applied to the starting of the given string.
const lastDay = “Thursday”;lastDay.padStart(9,’?’); //‘?Thursday’
If the given length is smaller than the string length, then it returns the default string “Thursday”.
Its structure must be like the following:
padStart( targetLength, padString );
targetLength is the end length value of the current string.
padString is the string value which will be padded to the current string.
padEnd() Method
padEnd method pads the string with desired string to the given length. Padding is applied to the end of the given string.
const lastDay = “Thursday”;lastDay.padStart(9,’?’); //‘?Thursday’
If the given length is smaller than the string length, then it returns the default string “Thursday”
It’s structure must be like the following:
padEnd(targetLength, padString);
targetLength is the end length value of the current string.
padString is the string value which will be padded to the current string.
repeat() Method
The repeat method is used in repeating the current string with the desired number of times which is set in parentheses as arguments.
For example:
const currentMonth = “September”;currentMonth.repeat(2); //“SeptemberSeptember”
replace() Method
Replace method has 2 arguments, first one is the string piece that is going to be replaced and the second is the string that is going to take over the place of the first string.
const currentMonth = “September”;currentMonth.replace(“Septem”, “Octo”); //October
search() Method
The search method returns the index of the first match of the argument string in the current string.
The search method is case-sensitive and matches a string with a regular expression. If there is not match found, it returns -1 as a result.
const currentMonth = “September”;currentMonth.search(“e”); // 1currentMonth.search(“ber”); // 6
slice() Method
The slice method returns a designated slice of the current string. You have to give a start index number and an optional end index.
const firstSummerMonth = “June”;firstSummerMonth.slice(1,3); // It returns ‘un’
As you can see above the first argument is the start index which is included, and the second argument is the end index which is the endpoint and not included in the sliced value. So, when you see index number 3 above, it says the end point is before index number 3.
split() Method
The split method splits the current string into an array of substrings. The split method does not change the original string. Most of the time we are going to use only one argument but it can take two arguments. The first argument is (“ “) used as a separator mostly, the string is split between words because it splits words from where it finds spaces in the current string.
However, if we use (“”) it will split all the letters.
For example, we have a string like the following:
const exampleString = “This is a great day”;exampleString.split(“ “); //[‘This’, ‘is’, ‘a’, ‘great’, ‘day’]const exampleString = “This is a great day”;exampleString.split(“”); //[‘T’, ‘h’, ‘i’, ‘s’, ‘ ‘, ‘i’, ‘s’, ‘ ‘, ‘a’, ‘ ‘, ‘g’, ‘r’, ‘e’, ‘a’, ‘t’, ‘ ‘, ‘d’, ‘a’, ‘y’]
As I mentioned above you can give a second argument for limiting the split process to a given number of words or letters.
exampleString.split(“ “, 3); //[‘This’, ‘is’, ‘a’]
subString() Method
The substring method extracts characters between two indices and returns a substring.
It does not change the original string. Negative values will be treated as zero and if the start index value is greater than the end value, arguments will automatically be swapped.
const myText = “This is my world”;myText.substring(1, 4); //’his’myText.substring(4, 1); // it will return us same value because indexes swapped
toLowerCase() Method
toLowerCase method converts a given string to a lowercase string. It takes no arguments.
const lastMonth = “MaRCh”;lastMonth.toLowerCase(); // march
toUpperCase() Method
toUpperCase method converts a given string to an uppercase string. It takes no arguments.
const lastMonth = “march”;lastMonth.toUpperCase(); // MARCH
trim() Method
If you have a string with unnecessary whitespaces, then you can use the trim method to prevent this whenever you need it. For example:
const todaysWeather = “ Gorgeous”;todaysWeather.trim(); //’Gorgeous’
trimStart() Method
You have the same functionality with the trim method but this time, you can trim whitespaces only at the start of a string specifically. It does not take any arguments or parameters.
const todaysWeather = “ Gorgeous “;todaysWeather.trimStart(); // ‘Gorgeous ‘
trimEnd() Method
As above, it has the same functionality but this time, you can trim whitespaces only at the end of a string specifically. It does not take any arguments or parameters.
const todaysWeather = “ Gorgeous “;todaysWeather.trimEnd(); // ‘ Gorgeous’
The Conclusion of this Article
We have looked into an important part of Javascript and we are going to dive into more detail with Array Methods in the next article.
See you on the next one.
Click here to go to Part 4