JavaScript String Methods

JavaScript String Methods

JavaScript Values

String length
String slice()
String substring()
String substr()
String replace()
String replaceAll()
String toUpperCase()
String toLowerCase()
String concat()
String trim()
String trimStart()
String trimEnd()
String padStart()
String padEnd()
String charAt()
String charCodeAt()
String split()

JavaScript String Length

The length property returns the length of a string

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

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()
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
If you omit the second parameter, substr() will slice out the rest of the string.

Replacing String Content

The replace() method replaces a specified value with another value in a string
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

JavaScript String ReplaceAll()

In 2021, JavaScript introduced the string method replaceAll()
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 set, otherwise a TypeError is thrown

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 trim()

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

JavaScript String trimStart()

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

JavaScript String trimEnd()

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

JavaScript String Padding

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

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

Home

About

Tutorial

EBooks

Menu