0% found this document useful (0 votes)
117 views21 pages

JavaScript String Methods Overview

Uploaded by

Maiwand Mangal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views21 pages

JavaScript String Methods Overview

Uploaded by

Maiwand Mangal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

 Tutorials  Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C

JavaScript String Methods


❮ Previous Next ❯

Basic String Methods


Javascript strings are primitive and immutable: All string methods produce a new string without altering the
original string.

String length String toUpperCase()


String charAt() String toLowerCase()
String charCodeAt() String concat()
String at() String trim()
String [ ] String trimStart()
String slice() String trimEnd()
String substring() String padStart()
String substr() String padEnd()
String repeat()
See Also: String replace()
String replaceAll()
String Search Methods String split()
String Templates

JavaScript String Length


The length property returns the length of a string:
 Tutorials 
Example Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = [Link];

Try it Yourself »

Extracting String Characters


There are 4 methods for extracting string characters:

The at(position) Method


The charAt(position) Method
The charCodeAt(position) Method
Using property access [] like in arrays

JavaScript String charAt()


The charAt() method returns the character at a specified index (position) in a string:

Example
let text = "HELLO WORLD";
let char = [Link](0);

Try it Yourself »

JavaScript String charCodeAt()


The charCodeAt() method returns the code of the character at a specified index in a string:

The method returns a UTF-16 code (an integer between 0 and 65535).
 Tutorials 
Example Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
let text = "HELLO WORLD";
let char = [Link](0);

Try it Yourself »

JavaScript String at()


ES2022 introduced the string method at() :

Examples
Get the third letter of name:

const name = "W3Schools";


let letter = [Link](2);

Try it Yourself »

Get the third letter of name:

const name = "W3Schools";


let letter = name[2];

Try it Yourself »

The at() method returns the character at a specified index (position) in a string.

The at() method is supported in all modern browsers since March 2022:

Note
The at() method is a new addition to JavaScript.

It allows the use of negative indexes while charAt() do not.


Now you can use [Link](-2) instead of charAt([Link]-2) .
 Tutorials  Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
Browser Support
at() is an ES2022 feature.

JavaScript 2022 (ES2022) is supported in all modern browsers since March 2023:

Chrome 94 Edge 94 Firefox 93 Safari 16.4 Opera 79

Sep 2021 Sep 2021 Oct 2021 Mar 2023 Oct 2021

Property Access [ ]

Example
let text = "HELLO WORLD";
let char = text[0];

Try it Yourself »

Note
Property access might be a little unpredictable:

It makes strings look like arrays (but they are not)


If no character is found, [ ] returns undefined, while charAt() returns an empty string.
It is read only. str[0] = "A" gives no error (but does not work!)

Example
let text = "HELLO WORLD";
Tutorials 
text[0] = "A";
Exercises  Services  
// Gives no error, but does not work
Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
Try it Yourself »

Extracting String Parts


There are 3 methods for extracting a part of a string:

slice(start, end)
substring(start, end)
substr(start, length)

JavaScript String slice()


slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: start position, and end position (end not included).

Example
Slice out a portion of a string from position 7 to position 13:

let text = "Apple, Banana, Kiwi";


let part = [Link](7, 13);

Try it Yourself »

Note
JavaScript counts positions from zero.

First position is 0.

Second position is 1.
 Tutorials 
Examples Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
If you omit the second parameter, the method will slice out the rest of the string:

let text = "Apple, Banana, Kiwi";


let part = [Link](7);

Try it Yourself »

If a parameter is negative, the position is counted from the end of the string:

let text = "Apple, Banana, Kiwi";


let part = [Link](-12);

Try it Yourself »

This example slices out a portion of a string from position -12 to position -6:

let text = "Apple, Banana, Kiwi";


let part = [Link](-12, -6);

Try it Yourself »

JavaScript String substring()


substring() is similar to slice() .

The difference is that start and end values less than 0 are treated as 0 in substring() .

Example

let str = "Apple, Banana, Kiwi";


let part = [Link](7, 13);
Try it Yourself
Tutorials 
» Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C

If you omit the second parameter, substring() will slice out the rest of the string.

JavaScript String substr()


substr() is similar to slice() .

The difference is that the second parameter specifies the length of the extracted part.

Example
let str = "Apple, Banana, Kiwi";
let part = [Link](7, 6);

Try it Yourself »

If you omit the second parameter, substr() will slice out the rest of the string.

Example
let str = "Apple, Banana, Kiwi";
let part = [Link](7);

Try it Yourself »

If the first parameter is negative, the position counts from the end of the string.

Example
let str = "Apple, Banana, Kiwi";
let part = [Link](-4);
Try it Yourself
Tutorials 
» Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C

Converting to Upper and Lower Case


A string is converted to upper case with toUpperCase() :

A string is converted to lower case with toLowerCase() :

JavaScript String toUpperCase()

Example
let text1 = "Hello World!";
let text2 = [Link]();

Try it Yourself »

JavaScript String toLowerCase()

Example
let text1 = "Hello World!"; // String
let text2 = [Link](); // text2 is text1 converted to lower

Try it Yourself »

JavaScript String concat()


concat() joins two or more strings:
 Tutorials 
Example Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
let text1 = "Hello";
let text2 = "World";
let text3 = [Link](" ", text2);

Try it Yourself »

The concat() method can be used instead of the plus operator. These two lines do the same:

Example

text = "Hello" + " " + "World!";


text = "Hello".concat(" ", "World!");

Note
All string methods return a new string. They don't modify the original string.

Formally said:

Strings are immutable: Strings cannot be changed, only replaced.

JavaScript String trim()


The trim() method removes whitespace from both sides of a string:

Example
let text1 = " Hello World! ";
let text2 = [Link]();
Try it Yourself »
Tutorials  Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C

JavaScript String trimStart()


ECMAScript 2019 added the String method trimStart() to JavaScript.

The trimStart() method works like trim() , but removes whitespace only from the start of a string.

Example

let text1 = " Hello World! ";


let text2 = [Link]();

Try it Yourself »

JavaScript String trimStart() is supported in all modern browsers since January 2020:

Chrome 66 Edge 79 Firefox 61 Safari 12 Opera 50

Apr 2018 Jan 2020 Jun 2018 Sep 2018 May 2018

JavaScript String trimEnd()


ECMAScript 2019 added the string method trimEnd() to JavaScript.

The trimEnd() method works like trim() , but removes whitespace only from the end of a string.

Example

let text1 = " Hello World! ";


let text2 = [Link]();
Try it Yourself »
Tutorials  Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
JavaScript String trimEnd() is supported in all modern browsers since January 2020:

Chrome 66 Edge 79 Firefox 61 Safari 12 Opera 50

Apr 2018 Jan 2020 Jun 2018 Sep 2018 May 2018

JavaScript String Padding


ECMAScript 2017 added two new string methods to JavaScript: padStart() and padEnd() to support
padding at the beginning and at the end of a string.

JavaScript String padStart()


The padStart() method pads a string from the start.

It pads a string with another string (multiple times) until it reaches a given length.

Examples
Pad a string with "0" until it reaches the length 4:

let text = "5";


let padded = [Link](4,"0");

Try it Yourself »

Pad a string with "x" until it reaches the length 4:

let text = "5";


let padded = [Link](4,"x");

Try it Yourself »
 Tutorials  Exercises  Services   Sign Up Log in


NoteCSS
HTML JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
The padStart() method is a string method.

To pad a number, convert the number to a string first.

See the example below.

Example

let numb = 5;
let text = [Link]();
let padded = [Link](4,"0");

Try it Yourself »

Browser Support
padStart() is an ECMAScript 2017 feature.

ES2017 is supported in all modern browsers since September 2017:

Chrome 58 Edge 15 Firefox 52 Safari 11 Opera 45

Apr 2017 Apr 2017 Mar 2017 Sep 2017 May 2017

padStart() is not supported in Internet Explorer.

JavaScript String padEnd()


The padEnd() method pads a string from the end.

It pads a string with another string (multiple times) until it reaches a given length.
 Tutorials 
Examples Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
let text = "5";
let padded = [Link](4,"0");

Try it Yourself »

let text = "5";


let padded = [Link](4,"x");

Try it Yourself »

Note
The padEnd() method is a string method.

To pad a number, convert the number to a string first.

See the example below.

Example

let numb = 5;
let text = [Link]();
let padded = [Link](4,"0");

Try it Yourself »

Browser Support
padEnd() is an ECMAScript 2017 feature.

ES2017 is supported in all modern browsers since September 2017:


 Tutorials  Exercises  Services   Sign Up Log in
Chrome 58 Edge 15 Firefox 52 Safari 11 Opera 45
HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
Apr 2017 Apr 2017 Mar 2017 Sep 2017 May 2017

padEnd() is not supported in Internet Explorer.

JavaScript String repeat()


The repeat() method returns a string with a number of copies of a string.

The repeat() method returns a new string.

The repeat() method does not change the original string.

Examples
Create copies of a text:

let text = "Hello world!";


let result = [Link](2);

Try it Yourself »

let text = "Hello world!";


let result = [Link](4);

Try it Yourself »

Syntax
[Link](count)

Parameters
Parameter Description
count Tutorials Required.
Exercises  Services 
The number of copies wanted.
 Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C

Return Value
Type Description

String A new string containing the copies.

Browser Support
repeat() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Safari 10 Opera 38

May 2016 Apr 2017 Jun 2017 Sep 2016 Jun 2016

repeat() is not supported in Internet Explorer.

Replacing String Content


The replace() method replaces a specified value with another value in a string:

Example
let text = "Please visit Microsoft!";
let newText = [Link]("Microsoft", "W3Schools");

Try it Yourself »
NoteTutorials 
 Exercises  Services   Sign Up Log in

HTML CSS JAVASCRIPT


The replace() SQL
method does not changePYTHON JAVA
the string it is PHP
called on. HOW TO [Link] C C++ C

The replace() method returns a new string.

The replace() method replaces only the first match

If you want to replace all matches, use a regular expression with the /g flag set. See examples below.

By default, the replace() method replaces only the first match:

Example
let text = "Please visit Microsoft and Microsoft!";
let newText = [Link]("Microsoft", "W3Schools");

Try it Yourself »

By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not work:

Example
let text = "Please visit Microsoft!";
let newText = [Link]("MICROSOFT", "W3Schools");

Try it Yourself »

To replace case insensitive, use a regular expression with an /i flag (insensitive):

Example
let text = "Please visit Microsoft!";
let newText = [Link](/MICROSOFT/i, "W3Schools");
Try it Yourself »
Tutorials  Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C

Note
Regular expressions are written without quotes.

To replace all matches, use a regular expression with a /g flag (global match):

Example
let text = "Please visit Microsoft and Microsoft!";
let newText = [Link](/Microsoft/g, "W3Schools");

Try it Yourself »

Note
You will learn a lot more about regular expressions in the chapter JavaScript Regular Expressions.

JavaScript String ReplaceAll()


In 2021, JavaScript introduced the string method replaceAll() :

Example
text = [Link]("Cats","Dogs");
text = [Link]("cats","dogs");

Try it Yourself »
The replaceAll() method allows you to specify a regular expression instead of a string to be replaced.
 Tutorials  Exercises  Services   Sign Up Log in
If the parameter is a regular expression, the global flag (g) must be set, otherwise a TypeError is thrown.
HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C

Example
text = [Link](/Cats/g,"Dogs");
text = [Link](/cats/g,"dogs");

Try it Yourself »

Note
replaceAll() is an ES2021 feature.

replaceAll() does not work in Internet Explorer.

Converting a String to an Array

If you want to work with a string as an array, you can convert it to an array.

JavaScript String split()


A string can be converted to an array with the split() method:

Example
[Link](",") // Split on commas
[Link](" ") // Split on spaces
[Link]("|") // Split on pipe
Try it Yourself »
Tutorials  Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C
If the separator is omitted, the returned array will contain the whole string in index [0].

If the separator is "", the returned array will be an array of single characters:

Example
[Link]("")

Try it Yourself »

Complete String Reference


For a complete String reference, go to our:

Complete JavaScript String Reference.

The reference contains descriptions and examples of all string properties and methods.

Test Yourself With Exercises

Exercise:
Convert the text into an UPPERCASE text:

let txt = "Hello World!";


txt = txt. ;

Submit Answer »
Start the Exercise
 Tutorials  Exercises  Services   Sign Up Log in

HTML
 CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO [Link] C C++ C

❮ Previous Next ❯

W3schools Pathfinder
Track your progress - it's free! Sign Up Log in

COLOR PICKER

 

 SPACES UPGRADE AD-FREE NEWSLETTER

GET CERTIFIED CONTACT US

Top Tutorials Top References


HTML Tutorial HTML Reference
CSS Tutorial CSS Reference
JavaScript Tutorial JavaScript Reference

 How To Tutorial
Tutorials 
SQL Tutorial
Exercises 
Python Tutorial
Services  SQL Reference

Python Reference
[Link] Reference
Sign Up Log in

HTML
 CSS [Link] Tutorial
JAVASCRIPT SQL PYTHON Bootstrap
JAVA Reference
PHP HOW TO [Link] C C++ C
Bootstrap Tutorial PHP Reference
PHP Tutorial HTML Colors
Java Tutorial Java Reference
C++ Tutorial Angular Reference
jQuery Tutorial jQuery Reference

Top Examples Get Certified


HTML Examples HTML Certificate
CSS Examples CSS Certificate
JavaScript Examples JavaScript Certificate
How To Examples Front End Certificate
SQL Examples SQL Certificate
Python Examples Python Certificate
[Link] Examples PHP Certificate
Bootstrap Examples jQuery Certificate
PHP Examples Java Certificate
Java Examples C++ Certificate
XML Examples C# Certificate
jQuery Examples XML Certificate

    

FORUM ABOUT CLASSROOM


W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy
policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by [Link].

Common questions

Powered by AI

The slice() method in JavaScript can handle negative index values. When a negative start or end index is provided, it counts from the end of the string. For example, string.slice(-3) will return the last three characters of the string. The substring() method treats negative indices as zero, effectively ignoring them, which means it starts counting from the beginning of the string regardless of the negative index. The substr() method, on the other hand, allows a negative first parameter to specify an offset from the string's end, but the second parameter specifies the length of the extracted part, which doesn't handle negative values. These differences in handling negative indices imply that developers need to carefully choose the appropriate method based on their use case—whether they need to count backwards from the end or handle negative indices as zeros .

The padStart() and padEnd() methods, introduced in ES2017, saw widespread adoption in modern browsers soon after their introduction. Chrome 58, Edge 15, Firefox 52, Safari 11, and Opera 45 all include support for these methods post-2017, with significant developer reliance starting as early as 2017—2018. Their ability to pad strings to a specified length with a given sequence is particularly useful in scenarios involving formatting, such as aligning numbers and text in logs or tabular data. While they are not supported in Internet Explorer, the influence has drastically benefited JavaScript developers by simplifying string manipulation code, aligning browser capabilities, and encouraging developers to move away from external utility libraries with these built-in functions .

The at() method and property access [] both retrieve a character at a specified position from a string in JavaScript. The at() method, introduced in ES2022, allows using both positive and negative indices to count forwards from the start or backwards from the end respectively. In contrast, property access [] treats negative indices as out of bounds, returning undefined instead of a character. Another difference is that at() was introduced to provide consistency across array methods and is supported in all modern browsers as of 2022, making it more reliable than property access, which has unpredictable behavior, such as returning undefined for out-of-bound indices. Additionally, property access does not raise errors when setting a character, despite not allowing the operation, while at() does not facilitate setting operations. These differences highlight the importance of using appropriate methods for string manipulations to prevent runtime issues due to unsupported features or inconsistent behavior .

The trim() method in JavaScript is used to remove whitespace from both the beginning and the end of a string, which is useful for sanitizing input data or processing formatted text. trimStart() and trimEnd(), introduced in ECMAScript 2019, are specialized versions that remove whitespace only from the start or end of a string, respectively. These methods are particularly useful in cases where whitespace trimming needs to be customized to specific parts of the string, enhancing performance by avoiding unnecessary trimming of the non-targeted end. Browser support for trimStart() and trimEnd() started after January 2020, with most modern browsers supporting them, such as Chrome from version 66 and Safari from version 11. The consistent support across browsers ensures that developers can reliably use these methods in web applications to handle string formatting tasks effectively .

The replaceAll() method should be used instead of replace() when a string operation requires replacing all occurrences of a substring or pattern in the target string, rather than just the first occurrence. While the replace() method replaces only the first match by default, replaceAll() ensures that every instance is replaced, making it useful for tasks like data cleanup or format conversions where multiple replacements are necessary. The compatibility implications are significant because replaceAll() is an ES2021 feature and is not supported in older browsers like Internet Explorer. Developers need to ensure the use of this method is supported by their target audience's browsers or provide polyfills or fallbacks in environments where replaceAll() is not available .

The methods toUpperCase() and toLowerCase() in JavaScript convert strings to upper and lower case, respectively. Performance-wise, they are similar as both involve traversing the string and modifying character representations, which are roughly equal in computational complexity. Their use cases vary: toUpperCase() is often used for standardizing input text for comparison or to ensure uniform casing in user interfaces, while toLowerCase() is used for creating case-insensitive data processing, such as searching or matching strings. Choosing between them depends primarily on the intended functionality within the application .

The default case-sensitive nature of the replace() method in JavaScript means that replacing operations will only match the exact case of the search string, and different casing will result in no replacement. This behavior is significant when working with user-generated content or case-variant data inputs, where expected matches might not occur as intended. To handle case insensitivity efficiently, developers can employ regular expressions with the /i flag to perform case-insensitive replacements. For example, `text.replace(/pattern/i, "replacement")` ensures that the pattern is matched regardless of character casing. Additionally, converting the entire string to a single case using toLowerCase() or toUpperCase() prior to replacement also ensures correct matches. These strategies help maintain robust and predictable behavior in text processing applications .

Both concat() and the plus operator (+) are used for string concatenation in JavaScript. The main difference lies in their syntax and performance nuances. The concat() method explicitly calls the function to concatenate strings and returns a new string without modifying the original ones, which can make code more readable by explicitly indicating a concatenation operation. The + operator is syntactically simpler and allows for more readable code when working with multiple variables or string formatting; however, it is not specifically a string method, making it more generic in its application. Developers might prefer the + operator for its brevity in straightforward and simple concatenation, while concat() is preferable for clearer, method-chainable operations where explicit method calls enhance readability or when avoiding unintended implicit type coercion is crucial .

The split() method converts a string into an array, enabling the use of array functionalities that aren't available with direct string indexing. While direct string indexing methods like charAt() or [] allow access to individual characters, they do not allow array operations such as sorting, filtering, reducing, or mapping over elements. Converting a string to an array with split() facilitates complex manipulations, like rearranging words, counting specific substrings, or performing bulk modifications based on patterns, which are not feasible with strings alone due to their immutable nature. Utilizing split() thus enhances flexibility and enables developers to leverage JavaScript's array processing capabilities, which are crucial for applications requiring complex string manipulations .

The immutability of strings in JavaScript means that string methods do not alter the original string but return a new one, requiring new memory allocation for each new string created. This immutability can lead to increased memory consumption and potential performance bottlenecks, particularly within loops or operations involving frequent string modifications. Each method call that modifies a string results in a completely new string, which can affect garbage collection and increase operational overhead when processing large datasets or executing numerous string operations. To mitigate these implications, developers should minimize unnecessary string operations, use string methods judiciously, and consider alternative solutions like arrays or string buffers (via the StringBuilder pattern) in performance-critical sections. Understanding and handling string immutability is vital for optimizing memory usage and performance in JavaScript applications .

You might also like