Open In App
Related Articles

JavaScript String Methods

Improve Article
Improve
Save Article
Save
Like Article
Like

JavaScript strings are the sequence of characters. In JavaScript, strings automatically convert the string to objects so that we can use string methods and properties also for primitive strings. It is used to represent and manipulate the sequence of characters.

In general, there are two ways to create a string in JavaScript. Either by using the new String() syntax or putting the value in quotes.

Example: This example, creates a string in JavaScript using the methods described above.

Javascript




let str1 = "Welcome to GeesforGeeks";
let str2 = new String("Welcome Geeks");
 
console.log(str1);
console.log(str2);


Output

Welcome to GeesforGeeks
[String: 'Welcome Geeks']

JavaScript String Methods and Property

String methods and properties are important to perform any operation on the given string, String indexes start from 0. The first character is in position 0 and the second in 1 and the same follows. We can call any of the pre-defined methods of JavaScript as it automatically converts from string primitive to objects.

Example:

 let gfg= "geeksforgeeks"

Property:

JavaScript String length Property: This property returns the number of characters present in the string. In the case of an array, this property returns the number of elements present in the array.

Example: This example describes the JavaScript String Length property.

JavaScript




// JavaScript to illustrate length property   
function func() {
    // length property for string
    console.log("GFG".length)
}
func();


Output:

3

Methods:

Below are the following methods of the string:

Method 1: JavaScript slice(startIndex, endIndex) Method

This method extracts a part of the string based on the given stating-index and ending-index and returns a new string.

Example: This example describes the JavaScript String slice() method.

javascript




let A = 'Geeks for Geeks';
b = A.slice(0,5);
c = A.slice(6,9);
d = A.slice(10);
 
console.log(b);
console.log(c);
console.log(d);


Output

Geeks
for
Geeks

Method 2: JavaScript substring(startIndex, endIndex) Method

This method returns the part of the given string from the start index to the end index. Indexing starts from zero (0).

Javascript




let str = "Mind, Power, Soul";
let part = str.substring(6, 11);
console.log(part);


Output:

Power

Method 3: JavaScript substr(start, length) Method

This method returns the specified number of characters from the specified index from the given string. It basically extracts a part of the original string.

Javascript




let str = "Mind, Power, Soul";
let part = str.substr(6, 5);
console.log(part);


Power

Method 4: JavaScript replace(replaceValue, replaceWithValue)

This method replaces a part of the given string with another string or a regular expression. The original string will remain unchanged.

Javascript




let str = "Mind, Power, Soul";
let part = str.replace("Power", "Space");
console.log(part);


Output:

Mind, Space, Soul

Method 5: JavaScript replaceAll(regexp | substr , newSubstr | function)

This method returns a new string after replacing all the matches of a string with a specified string or a regular expression. The original string is left unchanged after this operation.

Javascript




let str = "Mind, Power, Power,  Soul";
let part = str.replaceAll("Power", "Space");
console.log(part);


Output:

Mind, Space, Space,  Soul

Method 6: JavaScript toUpperCase(stringVariable)

This method converts all the characters present in the String to upper case and returns a new String with all characters in upper case. This method accepts single parameter stringVariable string that you want to convert in upper case.

Example: This example describes the JavaScript String toUpperCase() method.

javascript




let gfg = 'GFG '
let geeks = 'stands-for-GeeksforGeeks';
 
console.log(geeks.toUpperCase(geeks)) ;


Output:

STANDS-FOR-GEEKSFORGEEKS

Method 7: JavaScript toLowerCase(stringVariable)

This method converts all the characters present in the so lowercase and returns a new string with all the characters in lowercase.

Example: This example describes the JavaScript String toLowerCase() method.

javascript




let gfg = 'GFG ';
let geeks = 'stands-for-GeeksforGeeks';
 
console.log(geeks.toLowerCase(geeks));


Output:

stands-for-geeksforgeeks

Method 8: JavaScript concat(objectOfString) Method

This method combines the text of two strings and returns a new combined or joined string. To concatenate two strings, we use the concat() method on one object of string and send another object of string as a parameter. This method accepts one argument. The variable contains text in double quotes or single quotes.

Example: This example describes the JavaScript String concat() method.

javascript




let gfg = 'GFG ';
let geeks = 'stands for GeeksforGeeks';
 
// Accessing concat method on an object
// of String passing another object
// as a parameter
console.log(gfg.concat(geeks));


Output:

GFG stands for GeeksforGeeks

Method 9: JavaScript trim() Method

This method is used to remove either white spaces from the given string. This method returns a new string with removed white spaces. This method is called on a String object. This method doesn’t accept any parameter.

Example: This example describes the JavaScript String trim() method.

javascript




let gfg = 'GFG    ';
let geeks = 'stands-for-GeeksforGeeks';
 
// Storing new object of string
// with removed white spaces
let newGfg = gfg.trim();
 
// Old length
console.log(gfg.length);
 
// New length
console.log(newGfg.length)


Output:

7
3

Method 10: JavaScript trimStart() Method

This method removes whitespace from the beginning of a string. The value of the string is not modified in any manner, including any whitespace present after the string.

Javascript




let str = "  Soul";
console.log(str)
let part = str.trimStart();
console.log(part);


Output:

  Soul
Soul

Method 11: JavaScript trimEnd() Method

This method removes white space from the end of a string. The value of the string is not modified in any manner, including any white-space present before the string.

Javascript




let str = "Soul  ";
console.log(str)
let part = str.trimEnd();
console.log(part);


Output:

Soul    
Soul

Method 12: JavaScript padStart() Method

This method pad a string with another string until it reaches the given length. The padding is applied from the left end of the string.

Javascript




let stone = "Soul";
stone = stone.padStart(9,"Mind ");
console.log(stone);


Output:

Mind Soul

Method 13: JavaScript padEnd() Method

This method pad a string with another string until it reaches the given length. The padding is applied from the right end of the string.

Javascript




let stone = "Soul";
stone = stone.padEnd(10," Power");
console.log(stone);


Output:

Soul Power

Method 14: JavaScript charAt(indexOfCharacter) Method:

This method returns the character at the specified index. String in JavaScript has zero-based indexing.

Example: This example describes the JavaScript string charAt() method.

javascript




let gfg = 'GeeksforGeeks';
let geeks = 'GfG is the best platform to learn and\n'+
'experience Computer Science.';
 
// Print the string as it is
console.log(gfg);
 
console.log(geeks);
 
// As string index starts from zero
// It will return first character of string
console.log(gfg.charAt(0));
 
console.log(geeks.charAt(5));


Output:

GeeksforGeeks
GfG is the best platform to learn
and experience Computer Science.
G
s

Method 15: JavaScript charCodeAt(indexOfCharacter) Method

This method returns a number that represents the Unicode value of the character at the specified index. This method accepts one argument.

Example: This example describes the JavaScript String charCodeAt() Method.

javascript




let gfg = 'GeeksforGeeks';
let geeks = 'GfG is the best platform\n\
to learn and experience\n\
Computer Science.';
 
// Return a number indicating Unicode
// value of character at index 0 ('G')
console.log(gfg.charCodeAt(0));
console.log(geeks.charCodeAt(5));


Output:

71
115

Method 16: JavaScript split(character) Method

This method splits the string into an array of sub-strings. This method returns an array. This method accepts a single parameter character on which you want to split the string.

Example: This example describes the JavaScript String split() method.

javascript




let gfg = 'GFG '
let geeks = 'stands-for-GeeksforGeeks'
 
// Split string on '-'.
console.log(geeks.split('-'))


Output:

['stands', 'for', 'GeeksforGeeks']

String Method Summary:

Instance Methods

Description

at() Find the character at the specified index.
anchor() Creates an anchor element that is used as a hypertext target.
charAt() Returns that character at the given index of the string.
charCodeAt() Returns a Unicode character set code unit of the character present at the index in the string.
codePointAt() Return a non-negative integer value i.e, the code point value of the specified element.
concat() Join two or more strings together in JavaScript.
endsWith() Whether the given string ends with the characters of the specified string or not.
includes() Returns true if the string contains the characters, otherwise, it returns false.
indexOf() Finds the index of the first occurrence of the argument string in the given string.
lastIndexOf() Finds the index of the last occurrence of the argument string in the given string.
localeCompare() Compare any two elements and returns a positive number
match() Search a string for a match against any regular expression.
matchAll() Return all the iterators matching the reference string against a regular expression.
normalize() Return a Unicode normalization form of a given input string.
padEnd() Pad a string with another string until it reaches the given length from rightend.
padStart() Pad a string with another string until it reaches the given length from leftend.
repeat() Build a new string containing a specified number of copies of the string.
replace() Replace a part of the given string with some another string or a regular expression
replaceAll() Returns a new string after replacing all the matches of a string with a specified string/regex.
search() Search for a match in between regular expressions and a given string object.
slice() Return a part or slice of the given input string.
split() Separate given string into substrings using a specified separator provided in the argument.
startsWith() Check whether the given string starts with the characters of the specified string or not.
substr() Returns the specified number of characters from the specified index from the given string.
substring() Return the part of the given string from the start index to the end index.
toLowerCase() Converts the entire string to lowercase.
toLocaleLowerCase() Returns the calling string value converted to a lowercase letter.
toLocaleUpperCase() Returns the calling string value converted to a uppercase letter.
toUpperCase() Converts the entire string to uppercase.
toString() Return the given string itself.
trim() Remove the white spaces from both ends of the given string.
trimEnd() Remove white space from the end of a string.
trimStart() Remove white space from the start of a string.
valueOf() Return the value of the given string.

string[Symbol.iterator]()

This method is used to make String iterable. [@@iterator]() returns an iterator object which iterates over all code points of the String.

fromCharCode(n1, n2, …, nX)

This method is used to create a string from the given sequence of UTF-16 code units. This method returns a string, not a string object.

fromCodePoint(a1, a2, a3, ….)

This method in JavaScript that is used to return a string or an element for the given sequence of code point values (ASCII value).

isWellFormed()

This method is used to check if the string contains a lone surrogate or not

String.raw(str, …sub)

This is a static method that is used to get the raw string form of template literals. These strings do not process escape characters.

toWellFormed()

This method is used to return where all lone surrogates of this string are replaced with the Unicode replacement character

We have a complete list of Javascript string methods, to check those please go through this JavaScript String reference article.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 01 Aug, 2023
Like Article
Save Article
Similar Reads
Related Tutorials