Sitemap
Press enter or click to view image in full size
JavaScript String Methods

String Methods Every JavaScript Developer Should Know

--

In Javascript, a string is a primitive data type that represent a sequence of characters including letters, numbers, and symbols. JavaScript provides some useful functions (methods) that facilitate operations on strings when programming. This article outlines the most essential string methods that you should know. Unless in examples specified, each method uses variables assigned at the beginning; firstName, secondName, and fullName.

1. charAt()

The charAt method takes in an index and returns a new string that contains the single UTF-16 code (specific character) at the index location of whatever index that was passed in. The methods checks if the index passed in matches those that are within the length of the calling string and returns the character. If the index is outside of the string’s length, returns an empty string, and if no argument is passed it returns the character at the zero index.

const firstName = "James";const initialsIndex = 0;const nameInitial = firstName.charAt(initialsIndex);console.log(nameInitial); //Jconsole.log(firstName.charAt(firstName.length - 1)); //s

2. charCodeAt()

The method takes in an index value and returns an integer for the UTF-16 value of the character where the passed character is at. Just like the charAt method, the charCodeAt checks if the passed index matches any index in the string it is called on and returns the UTF-16 integer value (character code) of the character at that index. For character code greater that 655536, the charCodeAt(i+1) gets the other half of the value pair. An index that is outside of the string’s length returns NaN.

const nameInitialCode = firstName.charCodeAt(initialsIndex);console.log(`The ASCII code for first letter of my first name is ${nameInitialCode}`); //The ASCII code for first letter of my first name is 74console.log(firstName.charCodeAt(firstName.length - 1)); //115

3. concat()

The concat() method takes in multiple strings, joins them together, otherwise called string concatenation and produces a single string. It joins the strings passed as arguments to the string it is called on without changing the original strings. Non-string type arguments passed on the method get converted to string values before concatenating.

const secondName = "Rowa";const fullName = firstName.concat(" ", secondName);console.log(fullName); //James Rowaconsole.log(fullName.concat(["Nairobi", "Kenya"])); //James RowaNairobi,Kenya

4. includes()

This method carries out a case-sensitive search on the string it is called on to determine the presence or absence of the string passed in as argument and returns either true or false depending on the outcome of the search. The method takes in either the string to be searched for, but can take an additional optional argument (position) which is the position within the string at which the search begins. By default the position is 0.

The search is done from the default position and returns every character that matches the string passed as argument. If the returned characters match the input string in its exact order, the method returns true, otherwise it returns false.

console.log(fullName.includes("jam"));//false (case-sensitivity)console.log(fullName.includes("Jam"));//true
console.log(fullName.includes("Jam", 1));//false (position 1)
console.log(fullName.includes("R"));//TRUE

5. indexOf()

The methods takes in a substring as an argument that is to be searched for and searches the entire string it is called on for the first occurrence of the substring being searched for and returns the index value of the first occurrence. If the substring doesn’t exist, it returns -1. With a second argument as a number, the indexOf method returns the first occurrence of the argument substring at an index equal to or greater than the number passed.

const sentence ="My eldest brother, also called Rowa, and I share the name Rowa";const sharedName = "Rowa";const namesFirstIndex = sentence.indexOf(sharedName);console.log(`In the sentence, the name ${sharedName.toLocaleUpperCase()} appears first at index ${namesFirstIndex} and also at index ${sentence.indexOf(sharedName,namesFirstIndex + 1)}.`); //In the sentence, the name ROWA appears first at index 31 and also at index 58.// NB: we add one to the index the word first appears so that the second search just assumed the already existing first name and searches going forward from index 39.console.log(sentence.indexOf());//-1
console.log(sentence.indexOf(""));//0
console.log(sentence.indexOf("rowa"));//-1 name with lowercase r is non-existent in the sentence
console.log(sentence.indexOf(" ")); //2 space exists in the second index

Additional information on the method, especially a more detailed explanation on the parameters it take can be found on the MDN documentation.

6. match()

The match() method is used to match a string against a RegExp and retrieve the result of the match. The passed in parameter gets converted into a RegExp using the new RegExp(parameter) if it is not a RegExp object. Calling the match() method without passing in a parameter returns an empty array.

const regEx = /[A-Z]/g;console.log(fullName.match(regEx)); //['J', 'R']console.log(fullName.match("Rowa"));//['Rowa', index: 6, input: 'James Rowa', groups: undefined]const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";const regexp = /[A-E]/gi;const matches = alphabet.match(regexp);console.log(matches);// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

7. repeat()

This method returns a new string that repeats the original string a specified number of times concatenated together. The number of times the string is to be repeated must not be negative, must be less than infinity, and not overflow maximum size of string.

console.log(1, firstName.repeat()); //returns empty stringconsole.log(2, firstName.repeat(0)); //returns empty stringconsole.log(3, firstName.repeat(5)); //3 'JamesJamesJamesJamesJames'console.log(4, firstName.repeat(-3)); //Rangeerror

8. replace()

Just like the name states, this string method returns a new string in which one, a few, or all matches of a supplied pattern are replaced by the replacing string. The replacing string can be another string or even a function that gets called every time a match occurs, while the supplied pattern can be a simple string or a regular expression.

Get James Rowa’s stories in your inbox

Join Medium for free to get updates from this writer.

The method takes in a pattern (string or RegExp, (any value not any of the two gets coerced into a string)) and a replacement (string or function). A string replacement simply replaces the substring matched by the pattern, while a function gets invokes for every match and the value it returns becomes the replacement string. The method returns a new string without mutating the calling string. To carry out multiple replacements (global search and replacement), a RegExp with global flag is used or the replaceAll() is used instead, otherwise the method replaces the string pattern just once. Here is additional information on the replace() method.

const lastName = "Onyango";const myAka = fullName.replace(/James/i, lastName);console.log(myAka); //Onyango Rowaconsole.log("I am from East Africa".replace("East Africa", "Kenya"));//I am from Kenya

9. search()

The search() string is used to search for a match between a RegEx and the calling string. We may want to look for non-word or white space characters in a string, or just if there is a whitespace in a variable like the fullName above. The search() method simply calls the argument’s Symbol.search method on the string. This method returns the index within a string that matches a particular RegExp.

console.log(fullName.search("Rowa")); //6console.log(fullName.search(/[^\w]/g)); //5 the only whitespace in the fullName is at 5console.log(fullName.search(/[A-Z]/g)); //0 J at index 0 is the first capital letterconsole.log(fullName.search(/[[.]]/g));//-1 the fullName has no full stop
console.log(fullName.search(/AmEs/i)); //1

In the last example, /AmEs/i is a regular expression. AmEs is a pattern (to be used in a search). i is a modifier that modifies the search to be Case-Insensitive.

10. slice()

The slice() method fetches and returns a part of a string without modifying the calling string. To extract and return the section of the calling string and return it as a new one, the method takes in one or two parameters, either the indexStart, or both indexStart and indexEnd. The indexStart is the first character that gets included in the new string returned while the endIndex reps the first string that gets excluded from the returned substring. When fed with a negative number as the startIndex, the index is counted from the end of the string.

console.log(fullName.slice(5)); //Rowaconsole.log(fullName.slice(0, 5)); //Jamesconsole.log(fullName.slice(-5)); //Rowaconsole.log(fullName.slice(3, -3)); //es Rconsole.log(fullName.slice(0)); //James Rowaconsole.log(fullName.slice());//returns empty string

11. split()

When the split method gets called on a string and fed a pattern, it divides the string into an ordered list of substrings based on the input pattern and returns an array of the resulting substrings. The purpose of the patterns is to determine where each split occurs. The split() method can take a second optional parameter, a number, which is a non-negative integer that specifies a limit of the number of substrings to be included in the returned array. With the limit, the split() method splits the calling string on every occurrence of the pattern until a point where the substrings(now array elements) equal the limit parameter. A limit of zero returns an empty array.

console.log(fullName.split("")); //['J', 'a', 'm', 'e', 's', ' ', 'R', 'o', 'w', 'a']console.log(fullName.split("", 5)); //['J', 'a', 'm', 'e', 's']console.log(fullName.split(" ")); //['James', 'Rowa']console.log(fullName.split("", 0)); //[]console.log("I, James Rowa, do swear that, I understand string methods, JavaScript".split(",")//['I', ' James Rowa', ' do swear that', ' I understand string methods', ' JavaScript']);

12. substr()

The method acts on the calling string by taking in two parameter number values, first is the starting index (index of the first character to include), and second the number of characters to extend to. It then returns a portion of the string starting from the starting index, and extending to the number of characters specified. If the starting index is greater than or equal to the length of the calling string, the method returns an empty string, while it returns undefined if it is omitted. If the starting index is less than zero, the counting starts from the end of the string.

console.log(firstName.substr(1, 3)); //ameconsole.log(firstName.substr(5, 1)); //returns an empty stringconsole.log(firstName.substr(-1, 1)); //s

13. toLowerCase()

Simply returns the calling string value to lowercase. Since JavaScript strings are immutable, the conversion this method does not affect the string’s value

console.log(fullName.toLowerCase()); //james rowa

14. toUpperCase()

This method simply converts and returns a string it is called on converted to uppercase, and in instances where the calling value is not a string, it converts it into a string. Just like the toLowerCase() method, this method also does not affect the value of the calling string.

console.log(firstName.toUpperCase()); //JAMES

15. trim()

The trim() method removes (trims) unnecessary white spaces from both ends of a string thereby returning a new string without modifying the original string. If the method gets called on a string without any white spaces, the string just gets copied and a new one returned.

const whiteSpacedStr = " I have white spaces ";console.log(whiteSpacedStr.length);//21const trimmedStr = whiteSpacedStr.trim();console.log(trimmedStr.length);//19

There are two other more specific methods that perform more specific trimming, the trimStart() method which removes whitespace from the beginning of a string while trimLeft() does the exact same thing. trimRight does the opposite.

Conclusion

We have gone through some of the crucial string methods that a JavaScript developer needs at the tip of their fingers. Here is the Github repo for the article, you can edit or add methods. If you found this article helpful kindly leave a clap and follow me. Thank you.

--

--

James Rowa
James Rowa

Written by James Rowa

Self taught software developer. Community-taught at #100Devs. Software Developer Intern @Expivot