Open Playground
JS TutorialLesson #31

JavaScript String Methods

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

Basic String Methods

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

See Also: > String Tutorial > String Search > String Templates > String Reference

JavaScript String Length

The length property returns the length of a string:

Example

Example Code

javascript
Try it Yourself
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

let length = text.length;

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

Example Code

javascript
Try it Yourself
let text = "HELLO WORLD";

let char = text.charAt(0);

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).

Example

Example Code

javascript
Try it Yourself
let text = "HELLO WORLD";

let char = text.charCodeAt(0);

JavaScript codePointAt()

Examples

Example Code

javascript
Try it Yourself
let text = "HELLO WORLD";

let code = text.codePointAt(0);

JavaScript String at()

ES2022 introduced the string method at():

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:

Examples

Example Code

javascript
Try it Yourself
const name = "EA Academy";

let letter = name.at(2);
The at() method is a new addition to JavaScript. > It allows the use of negative indexes while charAt() do not.

Examples

Example Code

javascript
Try it Yourself
const name = "EA Academy";

let letter = name.at(-5);

Browser Support

at() is an ECMAScript 2022 feature.

JavaScript 2022 is supported in all modern browsers since March 2022:

Chrome 92Edge 92Firefox 90Safari 15.4Opera 78
Apr 2021Jul 2021Jul 2021Mar 2022Aug 2021

Property Access [ ]

Example

Example Code

javascript
Try it Yourself
let text = "HELLO WORLD";

let char = text[0];
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. > Propert access is read only, but str[0] = "A" gives no error in "sloppy mode".

Example (Sloppy Mode)

Example Code

javascript
Try it Yourself
let text = "HELLO WORLD";

// Try to change the first letter to "A"

try {

  text[0] = "A";

} catch(err) {

  text = err.message

}

Example (Strict Mode)

Example Code

javascript
Try it Yourself
"using strict";

let text = "HELLO WORLD";

// Try to change the first letter to "A"

try {

 text[0] = "A";

} catch(err) {

 text = err.message

}

JavaScript String concat()

concat() joins two or more strings:

Example

Example Code

javascript
Try it Yourself
let text1 = "Hello";

let text2 = "World";

let text3 = text1.concat(" ", text2);

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

Example

Example Code

javascript
Try it Yourself
text = "Hello" + " " + "World!";

text = "Hello".concat(" ", "World!");
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.

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

Example Code

javascript
Try it Yourself
let text = "Apple, Banana, Kiwi";

let part = text.slice(7, 13);
JavaScript counts positions from zero. > First position is 0. > Second position is 1.

Examples

Example Code

javascript
Try it Yourself
let text = "Apple, Banana, Kiwi";

let part = text.slice(7);

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

Example Code

javascript
Try it Yourself
let str = "Apple, Banana, Kiwi";

let part = str.substring(7, 13);

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.

Warning > The substr() method is deprecated in the latest JavaScript standard, > but is still officially defined in Annex B of the ECMAScript specification for backward compatibility. > You are strongly advised to use substring() or slice() instead.

Example

Example Code

javascript
Try it Yourself
let str = "Apple, Banana, Kiwi";

let part = str.substr(7, 6);

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

Example

Example Code

javascript
Try it Yourself
let str = "Apple, Banana, Kiwi";

let part = str.substr(7);

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

Example

Example Code

javascript
Try it Yourself
let str = "Apple, Banana, Kiwi";

let part = str.substr(-4);

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

Example Code

javascript
Try it Yourself
let text1 = "Hello World!";

let text2 = text1.toUpperCase();

JavaScript String toLowerCase()

Example

Example Code

javascript
Try it Yourself
let text1 = "Hello World!";       // String

let text2 = text1.toLowerCase();  // text2 is text1
converted to lower

JavaScript String isWellFormed()

The isWellFormed() method returns true if a string is well formed.

Otherwise it returns false.

A string is not well formed if it contains lone surrogates.

Examples

Example Code

javascript
Try it Yourself
let text = "Hello world!";

let result = text.isWellFormed();
Lone Surrogates > A lone surrogate is a Unicode surrogate code point that is not part of a valid surrogate pair > used to represent characters in UTF-16 encoding.

JavaScript String toWellFormed()

The String method toWellFormed() returns a new string where all "lone surrogates" are replaced with the Unicode replacement character (U+FFFD). ### Examples ``javascript let text = "Hello World \uD800"; let result = text.toWellFormed(); ` --- ## JavaScript String trim() The trim()` method removes whitespace from both sides of a string:

Example

Example Code

javascript
Try it Yourself
let text1 = "      Hello World!      ";

let text2 = text1.trim();

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

Example Code

javascript
Try it Yourself
let text1 = "     Hello World!     ";

let text2 = text1.trimStart();

Browser Support

trimStart() is an ECMAScript 2019 feature.

ES2019 is supported in all modern browsers since January 2020:

Chrome 66Edge 79Firefox 61Safari 12Opera 50
Apr 2018Jan 2020Jun 2018Sep 2018May 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

Example Code

javascript
Try it Yourself
let text1 = "     Hello World!     ";

let text2 = text1.trimEnd();

Browser Support

trimEnd() is an ECMAScript 2019 feature.

ES2019 is supported in all modern browsers since January 2020:

Chrome 66Edge 79Firefox 61Safari 12Opera 50
Apr 2018Jan 2020Jun 2018Sep 2018May 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

Example Code

javascript
Try it Yourself
let text = "5";

let padded = text.padStart(4,"0");
The padStart() method is a string method. > To pad a number, convert the number to a string first. > See the example below.

Example

Example Code

javascript
Try it Yourself
let numb = 5;

let text = numb.toString();

let padded = text.padStart(4,"0");

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.

Examples

Example Code

javascript
Try it Yourself
let text = "5";

let padded = text.padEnd(4,"0");
The padEnd() method is a string method. > To pad a number, convert the number to a string first. > See the example below.

Example

Example Code

javascript
Try it Yourself
let numb = 5;

let text = numb.toString();

let padded = text.padEnd(4,"0");

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

Example Code

javascript
Try it Yourself
let text = "Hello world!";

let result = text.repeat(2);

Syntax

string.repeat(count)

Parameters

ParameterDescription
countRequired. The number of copies wanted.

Return Value

TypeDescription
StringA new string containing the copies.

Replacing String Content

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

Example

Example Code

javascript
Try it Yourself
let text = "Please visit Microsoft!";

let newText = text.replace("Microsoft", "EA Academy");
The replace() method does not change the string it is called on. > 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

Example Code

javascript
Try it Yourself
let text = "Please visit Microsoft and Microsoft!";

let newText = text.replace("Microsoft", "EA Academy");

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

Example

Example Code

javascript
Try it Yourself
let text = "Please visit Microsoft!";

let newText = text.replace("MICROSOFT", "EA Academy");

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

Example

Example Code

javascript
Try it Yourself
let text = "Please visit Microsoft!";

let newText = text.replace(/MICROSOFT/i, "EA Academy");
Regular expressions are written without quotes.

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

Example

Example Code

javascript
Try it Yourself
let text = "Please visit Microsoft and Microsoft!";

let newText = text.replace(/Microsoft/g, "EA Academy");
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

Example Code

javascript
Try it Yourself
text = text.replaceAll("Cats","Dogs");

text = text.replaceAll("cats","dogs");

The replaceAll() method allows you to specify a regular expression instead of a string to be replaced.

If the parameter is a regular expression, the global flag (g) must be set, otherwise a TypeError is thrown.

Example

Example Code

javascript
Try it Yourself
text = text.replaceAll(/Cats/g,"Dogs");

text = text.replaceAll(/cats/g,"dogs");
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:

Syntax

Example Code

javascript
Try it Yourself
text.split("")     // Split on characters

text.split(",")    // Split on commas

text.split(" ")    // Split on spaces

text.split("|")    // Split on pipe

Examples

Example Code

javascript
Try it Yourself
let text = "Hi fox!";

const myArr = text.split("");

Using split("") Can be Unsafe

Using split("") is unsafe for strings containing emojis or complex characters.

The method splits by UTF-16 code units and will break surrogate pairs.

split("") is always unsafe for emojis. It will slice right through them and create broken, corrupt code fragments.

split(" ") is usually safe for words, even if they have emojis inside them, as long as the emoji is not glued right next to a space you are splitting on.

Summary of Options:

  • text.split("") is most unsafe It breaks up 4-byte emojis (like 💩 becomes ['\uD83D', '\uDCA9']).
  • Spread [...text] is partially safe: It works for simple emojis like 💩 or 🔥, but destroys complex emojis like 👨‍👩‍👧‍👦, 🧑‍⚕️ (doctor), or flags.
  • Intl.Segmenter is 100% Safe: It handles every emoji, accent, and complex characters.

Examples

Example Code

javascript
Try it Yourself
let text = "👨‍👩‍👧‍👦";

const myArr = text.split("");

Complete JavaScript Reference > For a complete reference to all JavaScript properties and methods, with full descriptions and many examples, go to: > EA Academy' Full JavaScript Reference. > The reference inludes all JavaScript updates from 1999 to 2025.


Interactive Code Examples

JS Example 1

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

let length = text.length;

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let text = "HELLO WORLD";

let char = text.charAt(0);

JS Example 3

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let text = "HELLO WORLD";

let char = text.charCodeAt(0);

Examples

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let text = "HELLO WORLD";

let code = text.codePointAt(0);

Examples

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const name = "EA Academy";

let letter = name.at(2);

Examples

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const name = "EA Academy";

let letter = name.at(-5);