Tutorials Tonight's Logo

JAVASCRIPT STRING METHODS


What Are String Methods In Javascript?

Javascript String methods are special build-in functions that perform a specific task when applied on any valid string. These methods return a new string based on the methods applied without modifying the original string.

Any simple string like "Brenden Eich" (creator of JavaScript) is a primitive value, so it does not have any methods or properties with it but javascript treats these primitive values as objects when we execute it with some method or properties.

Here is a simple example of a string method, find the position of "Eich" in the string.

Test String = "Brenden Eich"

Using indexOf() method


Javascript String Length

Apart from multiple string methods in JavaScript, there is also a string property to find the length of the string.

To find the length of the string using the length property on the string, return a number of code units in the string including spaces.

The length is only a read-only data property of a string.

The length of an empty string is 0.

const name = "Brenden Eich";
const lengthOfName = name.length; // output: 12
console.log("lengthOfName = " + lengthOfName);
const empty = "";
console.log(empty.length);
▶ Try It

Javascript String Methods List

Here is a list of all string methods in JavaScript, we will go into detail with each method further in the article. Click on any method to jump to the section.

  1. charAt()
  2. charCodeAt()
  3. concat(str1, str2, ...)
  4. includes()
  5. endsWith()
  6. indexOf()
  7. lastIndexOf()
  8. match()
  9. matchAll()
  10. repeat()
  11. replace()
  12. replaceAll()
  13. search()
  14. slice()
  15. split()
  16. startsWith()
  17. substr()
  18. toLowerCase()
  19. toUpperCase()
  20. toString()
  21. trim()
  22. valueOf()

Now let's look at each String methods in detail.


1. charAt in javascript

The charAt() string method in javascript returns a character at the specific index of the given string.

The charAt() method takes an argument which is index value. An index value of a string starts with 0, which means the first character has an index value of 0, the second character has an index value of 1, and so on.

The default an index value is 0, if the index value is out of range or can not be converted to an integer then this method returns the first character of the string.

const str = "Brenden Eich";
console.log(str.charAt()); //default index value = 0, return first character
console.log(str.charAt(1));
console.log(str.charAt(13)); // index out of range, return empty string
console.log(str.charAt(5));
▶ Try It

2. charCodeAt in javascript

The charCodeAt() string method in javascript returns the Unicode value of the character present at the given index of the string.

The Unicode value lies between 0 and 65535 which represent the UTF-16 code unit of character at the specified index.

The charCodeAt() method takes an argument which is index value.

The default value of index is 0 if the index value is not given or it can't be converted to a string.

If the index value is out of range then this method returns NaN.

const str = "Brenden Eich";
console.log(str.charCodeAt()); //default index value = 0
console.log(str.charCodeAt("x")); //default index value = 0
console.log(str.charCodeAt(1));
console.log(str.charCodeAt(13)); // return NaN
▶ Try It

3. concat in javascript

The concat() string method in javascript concatenates the passed string to the calling string and return a new string.

The concat() method can take any number of strings as an argument.

If the passed argument is not a string then it converts it to string and then concatenates it.

const firstName = "Brenden";
const lastname = "Eich"
console.log(firstName.concat(" ", lastname));
▶ Try It

Note: for concatenation of string it is suggested to use + or += instead of the concat method.



4. String includes in javascript

The includes() string method in javascript determines whether the string in the argument is present in the calling string.

If the string is present then the method returns true, if not then it returns false.

The string matching of includes() method is case-sensitive.

const sentence = "Carbon emittion is increasing Day by day.";
const word1 = "day";
const word2 = "Day";
const word3 = "DAY";
console.log(sentence.includes(word1));
console.log(sentence.includes(word2));
console.log(sentence.includes(word3));
▶ Try It

5. endsWith in javascript

The endsWith() string method in javascript determines whether the string ends with a specified string or not. If it ends with specified string then it returns true, else returns false.

The string to be checked for the ending is passed as an argument.

There is another length argument, which is optional. It specifies the length of the string to be checked for.

Please note that endsWith() method is case sensitive.

const question = "What is DOM?";
const endString = "?";
console.log(question.endsWith(endString));
console.log(question.endsWith(endString, 10));
▶ Try It

6. indexOf in javascript

The indexOf() string method in javascript searches the first occurrence of a character or substring into a string.

If a character or substring is present in the string then it returns the index of the first occurrence of it, if it is not present then it returns -1. The search string is case-sensitive.

If no search string is provided to the method then default search string is 'undefined'. Example 'undefined'.indexOf() will return 0.

There is an optional argument that defines the start index from where it starts in the string.

const sentence = "Carbon emittion is increasing day by day";
const char = "day";
console.log(sentence.indexOf(char));
console.log(sentence.indexOf(char, 40));
▶ Try It

7. String lastIndexOf javascript

The lastIndexOf() string method in javascript searches the last occurrence of a character or substring into a string by searching the substring from backward of the string.

If a character or substring is present in the string then it returns the index of the last occurrence of it in the string, if it is not present then it returns -1.

If no character or substring is passed then default search is for 'undefined'. Example 'undefined'.lastIndexOf() will return 0.

There is an optional argument which fromIndex. Its default value is +Infinity. If fromIndex >= str.length then whole string searched.

const sentence = "Carbon emittion is increasing day by day";
const char = "day";
console.log(sentence.lastIndexOf(char));
console.log(sentence.lastIndexOf(char, 20));
▶ Try It


8. match in javascript

The match() string method in javascript use regex to match the string. It returns the output as an array with matched character or string as its element.

If the parameter passed is not a regular expression then it is implicitly converted to RegExp by using new RegExp(regexp).

const series = "bdWg2AdjgH4du5jUgT";
const regex = /[A-Z0-9]/g;
console.log(series.match(regex));
▶ Try It

9. matchAll in javascript

The matchAll() string method in javascript returns an iterator to all results matching the string against the regex.

const series = "bdWg2AdjgH4du5jUgT";
const regex = /[A-Z0-9]/g;
const array = [...series.matchAll(regex)];
console.log(array);
console.log(array[0])
▶ Try It

10. repeat in javascript

The repeat() method creates and returns a new string that contains a specified number of copies of a passed string, concatenated together.

A number is passed as an argument in the method as the number of times string should be repeated. The number must be between 0 and +Infinity. Float value will be converted to Integer when passed.

const str = "Eat Sleep Code Repeat, ";
console.log(str.repeat(0));
console.log(str.repeat(3.5));
console.log(str.repeat(2));
▶ Try It

11. replace in javascript

The replace() method returns a new string after replacing some or all occurrences of some pattern with another replacement in the given string.

The pattern can be a string or regex, and the replacement can be a string to be replaced or a function to be called for each match.

When the pattern is string only the first occurrence of it will be replaced.

const str = "Carbon emittion is increasing day by day.";
console.log(str.replace(/day/g, "year")); // all replace
console.log(str.replace("day", "year")); // only first occurance replace
▶ Try It

12. replaceAll in javascript

The replaceAll() method returns a new string after replacing all occurrences of some pattern with another replacement in the given string.

The pattern can be a string or regex, and the replacement can be a string to be replaced or a function to be called for each match.

When using regex in replaceAll() method using a global flag with it otherwise it will throw a 'TypeError'.

const str = "Carbon emittion is increasing day by day.";
console.log(str.replaceAll("day", "year"));
▶ Try It

13. search in javascript

The search() string method in javascript uses regex to search for a pattern in a string, if a pattern exists in the string then it returns the index of the first occurrence of the pattern.

const str = "kjhsfdbAjdbj";
console.log(str.search(/[A-Z]/g));
▶ Try It

14. slice in javascript

The slice() string method in javascript extracts a part of the string and returns it as a new string.

str.slice( startIndex, endIndex)

The slice() takes 2 argument, the first argument is the start index for the slicing string and the second is the end of the slicing string, where the second argument is optional.

When the second argument is not passed then the string is sliced from 'startIndex' to the end of the string.

The slice() method also accepts negative value, where -1 represents the last index

const sentence = "Carbon emittion is increasing day by day";
console.log(sentence.slice(5, 15));
console.log(sentence.slice(5));
console.log(sentence.slice(-15, -5));
▶ Try It


15. split in javascript

The split() string method in javascript divides a string into a list of substrings based on the split value and returns this element by putting it in an array.

The split() method accepts 2 arguments, first is separator: it can be a string or regex which describe where each split should occur (it is optional), second is limit: it is a number which limits the number of elements in the returning array (it is also optional).

const sentence = "Carbon emittion is increasing day by day";
console.log(sentence.split());
console.log(sentence.split(" "));
console.log(sentence.split("is"));
▶ Try It

16. startsWith in javascript

The startsWith() string method in javascript determines whether a string starts with some string or not. If it starts with the desired string then it returns true else return false.

The search string is passed as an argument. There is also an optional argument that defines the position where the method should start checking.

const sentence = "Carbon emittion is increasing day by day";
console.log(sentence.startsWith("Car"));
console.log(sentence.startsWith("bon", 3));
▶ Try It

17. substr in javascript

The substr() string method in javascript returns a part of the string, starting at a specific index and ending after a given number of characters.

const sentence = "Carbon emittion is increasing day by day";
console.log(sentence.substr(10, 6));
console.log(sentence.substr(10));
▶ Try It

18. toLowerCase in javascript

The toLowerCase() string method in javascript returns a new string by converting the calling string to lowercase.

const sentence = "CARBON EMITTION IS INCREASING DAY BY DAY";
console.log(sentence.toLowerCase());
▶ Try It

19. toUpperCase in javascript

The toUpperCase() string method in javascript returns a new string by converting the calling string to uppercase.

const sentence = "carbon emittion is increasing day by day";
console.log(sentence.toUpperCase());
▶ Try It

20. toString in javascript

The toString() string method in javascript returns a string representing the specified object.

This method also convert numbers to strings in a different number system. You can pass 2 to convert any decimal number to binary number.

const str = new String("hello World!");
console.log(str.toString(str));
const num = 20;
console.log(num.toString(2));
▶ Try It

21. trim in javascript

The trim() string method in javascript removes whitespaces from both ends of the string. Whitespaces are space, tabs, newline, etc.

const str = "    TutorialsTonight    ";
console.log(str.trim());
▶ Try It

22. valueOf in javascript

The valueOf() string method in javascript returns the primitive value of a String object.

const str = new String("hello world");
console.log(str.valueOf(str));
▶ Try It


Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.