JavaScript String Methods

By | August 22, 2022

String methods help you to work with strings.

String Methods and Properties

Primitive values, like “John Doe”, cannot have properties or methods (because they are not objects).

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

JavaScript String Length

The length property returns the length of a string:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Properties</h2>
<p>The length property returns the length of a string:</p>
<p id="demo"></p><script>
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = text.length;
</script>​
</body>
</html>

Result:

JavaScript String Properties

The length property returns the length of a string:

26

Extracting String Parts

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

  • slice(startend)
  • substring(startend)
  • substr(startlength)

JavaScript String slice()

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

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

Example

Slice out a portion of a string from position 7 to position 13 (13 not included):

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The slice() method extract a part of a string
and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.slice(7,13); 
</script>
</body>
</html>

Result:

JavaScript String Methods

The slice() method extract a part of a string and returns the extracted parts in a new string:

Banana

Note

JavaScript counts positions from zero.

First position is 0.

Second position is 1.

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

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

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The slice() method extract a part of a string
and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.slice(-12,-6);
</script>
</body>
</html>

Result:

JavaScript String Methods

The slice() method extract a part of a string and returns the extracted parts in a new string:

Banana

If you omit the second parameter, the method will slice out the rest of the string:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The slice() method extract a part of a string
and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.slice(7);
</script>
</body>
</html>

Result:

JavaScript String Methods

The slice() method extract a part of a string and returns the extracted parts in a new string:

Banana, Kiwi

or, counting from the end:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The slice() method extract a part of a string
and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.slice(-12);
</script>
</body>
</html>

Result:

JavaScript String Methods

The slice() method extract a part of a string and returns the extracted parts in a new string:

Banana, Kiwi

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

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The substring() method extract a part of a string and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substring(7,13);
</script>
</body>
</html>

Result:

JavaScript String Methods

The substring() method extract a part of a string and returns the extracted parts in a new string:

Banana

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

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The substr() method extract a part of a string
and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(7,6);
</script>
</body>
</html>

Result:

JavaScript String Methods

The substr() method extract a part of a string and returns the extracted parts in a new string:

Banana

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

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The substr() method extract a part of a string
and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(7);
</script>
</body>
</html>​

Result:

JavaScript String Methods

The substr() method extract a part of a string and returns the extracted parts in a new string:

Banana, Kiwi

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

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The substr() method extract a part of a string
and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(-4);
</script>
</body>
</html>

Result:

JavaScript String Methods

The substr() method extract a part of a string and returns the extracted parts in a new string:

Kiwi

Replacing String Content

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

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
​<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.replace("Microsoft","W3Schools");
}
</script>
</body>
</html>

Result:

Run This Code in your browser.

Note

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

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft and Microsoft!</p>
<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML; 
  document.getElementById("demo").innerHTML =
  text.replace("Microsoft","W3Schools");
}
</script>
</body>
</html>

Result:

Run This Code in your browser.

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

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Try to replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML; 
  document.getElementById("demo").innerHTML =
  text.replace("MICROSOFT","W3Schools");
}
</script>
<p>The replace() method is case sensitive. MICROSOFT (with upper-case) will not be replaced.</p>
</body>
</html>

Result:

Run This Code in your browser.

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

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML; 
  document.getElementById("demo").innerHTML =
  text.replace(/MICROSOFT/i,"W3Schools");
}
</script>
</body>
</html>

Result:

Run This Code in your browser.

Note

Regular expressions are written without quotes.

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

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Replace all occurrences of "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft and Microsoft!</p>
<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML; 
  document.getElementById("demo").innerHTML =
  text.replace(/Microsoft/g,"W3Schools");
}
</script>
</body>
</html>

Result:

Run This Code in your browser.

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

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Convert string to upper case:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Hello World!</p>
<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.toUpperCase();
}
</script>
</body>
</html>

Result:

Run This Code in your browser.

JavaScript String toLowerCase()

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Convert string to lower case:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Hello World!</p>
<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.toLowerCase();
}
</script>
</body>
</html>

Result:

Run This Code in your browser.

JavaScript String concat()

concat() joins two or more strings:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The concat() method joins two or more strings:</p>
<p id="demo"></p>
<script>
let text1 = "Hello";
let text2 = "World!";
let text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>
</body>
</html>

Result:

JavaScript String Methods

The concat() method joins two or more strings:

Hello World!

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

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The trim() Method</h2>
<p id="demo"></p>
<script>
let text1 = "     Hello World!     ";
let text2 = text1.trim();
document.getElementById("demo").innerHTML =
"Length text1=" + text1.length + "<br>Length2 text2=" + text2.length;
</script>
</body>
</html>

Result:

JavaScript Strings

The trim() Method

Length text1=22
Length2 text2=12

JavaScript String Padding

ECMAScript 2017 added two String methods: 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 with another string:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The padStart() method pads a string with another string:</p>
<p id="demo"></p>
<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padStart(4,"x");
</script>
</body>
</html>

Result:

JavaScript String Methods

The padStart() method pads a string with another string:

xxx5

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The padStart() method pads a string with another string:</p>
<p id="demo"></p>
<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padStart(4,"0");
</script>
</body>
</html>

Result:

JavaScript String Methods

The padStart() method pads a string with another string:

0005

Note

The padStart() method is a string method.

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

See the example below.

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The padStart() method pads a string with another string:</p>
<p id="demo"></p>
<script>
let numb = 5;
let text = numb.toString();
document.getElementById("demo").innerHTML = text.padStart(4,0);
</script>
</body>
</html>

Result:

JavaScript String Methods

The padStart() method pads a string with another string:

0005

Browser Support

padStart() is an ECMAScript 2017 feature.

It is supported in all modern browsers:

ChromeEdgeFirefoxSafariOpera
YesYesYesYesYes

padStart() is not supported in Internet Explorer.

JavaScript String padEnd()

The padEnd() method pads a string with another string:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The padEnd() method pads a string with another string:</p>
<p id="demo"></p>
<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padEnd(4,"x");
</script>
</body>
</html>

Result:

JavaScript String Methods

The padEnd() method pads a string with another string:

5xxx

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The padEnd() method pads a string with another string:</p>
<p id="demo"></p>
<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padEnd(4,"0");
</script>
</body>
</html>

Result:

JavaScript String Methods

The padEnd() method pads a string with another string:

5000

Note

The padEnd() method is a string method.

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

See the example below.

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The padEnd() method pads a string with another string:</p>
<p id="demo"></p>
<script>
let numb = 5;
let text = numb.toString();
document.getElementById("demo").innerHTML = text.padEnd(4,"x");
</script>
</body>
</html>

Result:

JavaScript String Methods

The padEnd() method pads a string with another string:

5xxx

Browser Support

padEnd() is an ECMAScript 2017 feature.

It is supported in all modern browsers:

ChromeEdgeFirefoxSafariOpera
YesYesYesYesYes

padEnd() is not supported in Internet Explorer.

Extracting String Characters

There are 3 methods for extracting string characters:

  • charAt(position)
  • charCodeAt(position)
  • Property access [ ]

JavaScript String charAt()

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

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The charAt() method returns the character at a given position in a string:</p>
<p id="demo"></p>
<script>
var text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text.charAt(0);
</script>
</body>
</html>

Result:

JavaScript String Methods

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

H

JavaScript String charCodeAt()

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

The method returns a UTF-16 code (an integer between 0 and 65535).

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The charCodeAt() method returns the unicode of the character at a given position in a string:</p>
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text.charCodeAt(0);
</script>
</body>
</html>

Result:

JavaScript String Methods

The charCodeAt() method returns the unicode of the character at a given position in a string:

72

Property Access

ECMAScript 5 (2009) allows property access [ ] on strings:

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>ECMAScript 5 allows property access on strings:</p>
<p id="demo"></p>
<script>
var str = "HELLO WORLD";
document.getElementById("demo").innerHTML = str[0];
</script>
</body>
</html>

Result:

JavaScript String Methods

ECMAScript 5 allows property access on strings:

H

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

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>ES5 (2009) allows property acces on strings. But read only:</p>
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
text[0] = "A";  // Does not work
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result:

JavaScript String Methods

ES5 (2009) allows property acces on strings. But read only:

HELLO WORLD

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

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Display the first array element, after a string split:</p>
<p id="demo"></p>
<script>
let text = "a,b,c,d,e,f";
const myArray = text.split(",");
document.getElementById("demo").innerHTML = myArray[0];
</script>
</body>
</html>​

Result:

JavaScript String Methods

Display the first array element, after a string split:

a

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

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Using String.split():</p>
<p id="demo"></p>
<script>
let text = "Hello";
const myArr = text.split("");
text = "";
for (let i = 0; i < myArr.length; i++) {
  text += myArr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result:

JavaScript String Methods

Using String.split():

H
e
l
l
o

Leave a Reply

Your email address will not be published. Required fields are marked *