JavaScript String Methods—A Complete Guide (Updated 2022)

String is one of the fundamental data types of JavaScript. Basically, every application has to do some string processing at some point. String handling usually involves finding length, checking if a character exists, splitting the string based on a separator, and so on. These operations are so common, that JavaScript includes ready-made logic for carrying out such operations.

This way you, the developer, don’t have to spend time reinventing the string processing logic from project to project.

This is a complete guide to JavaScript string methods. You will learn useful built-in functionality that streamlines working with strings.

Notice that all the string methods on this list do not modify the original string. Instead, they return a new result string that represents the modified original string.

Length

To get the length of a string in JavaScript, you need to access the length property of a string.

Notice that the length is not a method! But because many developers associate it with string methods, I felt this list wouldn’t be complete without including it.

String.length

Let’s see an example. This piece of code prints the length of a string:

let name = "Jack"
console.log(name.length)

Output:

4

If the string is empty, its length will be 0.

The length property is the only property on the list. From this point on, you’ll only deal with string methods.

String.replace()

The replace() method replaces the first occurrence of specific characters in a string with a replacement string. This method then returns the new string with the replaced value.

Here is the generic syntax:

String.replace(pattern, replacement)

Let’s have a look at some examples.

First, the most usual use case for the replace() method is to replace a substring with another:

const message = "I love cats"

const newMessage = message.replace("cat", "dog")
console.log(newMessage)

Output:

I love dogs

But this method only replaces the first occurrence. To replace all the occurrences of a substring in a string, you can use regular expressions.

If you aren’t familiar with regular expressions (regex), make sure to read this guide first. Otherwise, the following example won’t make much sense.

For example, let’s replace all the occurrences of a dash in a string that is in the kebab case:

const message = "my-favorite-day-is-saturday"

const newMessage = message.replace(/-/g, " ")
console.log(newMessage)

Output:

my favorite day is saturday

String.indexOf()

In JavaScript, the indexOf() method returns the index at which a specific character or substring occurs on a string for the first time.

If no match is found, the method returns -1.

Here is the generic syntax of the method:

String.indexOf(searchString)

As an example, let’s use the indexOf() method to find the index at which the word “one” occurs in a message:

const message = "This is the one!"

const idx = message.indexOf("one")
console.log(idx)

Output:

12

And to highlight the fact that this method only returns the index of the first occurrence, consider this:

const message = "This is the one one one one one one one!"

const idx = message.indexOf("one")
console.log(idx)

Output:

12

String.lastIndexOf()

The lastIndexOf() method returns the last index at which a specific search string occurs in a string.

The method returns -1 if no matching strings are found.

For efficiency reasons, this method starts the search from the last character of the string. You’ll notice this in a later example.

Here’s the generic syntax of the lastIndexOf() method:

String.lastIndexOf(searchString)

As an example, let’s find the index at which the word “day” occurs in a message:

const message = "Today is the day that is my favorite day of the year!"

const idx = message.lastIndexOf("day")
console.log(idx)

Output:

37

You can also specify another optional argument to the lastIndexOf() method call. This argument determines the index after which the search starts.

So you can use this second argument to neglect the last 5 letters for example.

const message = "one two"

const idx = message.lastIndexOf("two", 2)
console.log(idx)

Output:

-1

The result is -1 because the search starts at index 2 from the right-hand side. In other words, the algorithm checks if the word “two” occurs after ignoring the last 2 letters. In other words, it checks the string “one t” which doesn’t contain “two”.

String.startsWith()

As the name suggests, the startsWith() method checks if a given string starts with a specific substring.

  • If it does, the method returns true.
  • If it doesn’t, the method returns false.

Here is the generic syntax:

String.startsWith(searchString)

For example, let’s check if a message starts with “Hi, editor”:

const message = "Hi, editor. It's me. How are you doing?"

const isSpam = message.startsWith("Hi, editor")
console.log(isSpam)

Output:

true

You can add another optional argument to the startsWith() method. This argument lets you move the starting index of the word.

For example, let’s check if the 10th character of a string starts with the word “goal”:

const message = "That is a goal"

const goal = message.startsWith("goal", 10)
console.log(goal)

Output:

true

String.endsWith()

The endsWith() method checks if a given string ends at a specific substring.

  • If it does, the method returns true.
  • If it doesn’t, the method returns false.

Here is the generic syntax:

String.endsWith(searchString)

For instance, let’s check if a message ends with “Bye bye!”:

const message = "I'm going now. Bye bye!"

console.log(message.endsWith("Bye bye!"))

Output:

true

You can add a second (optional) argument to the endsWith() method. This argument lets you specify a custom end index for your string.

For example, let’s check if the previous example ends with “now” when terminated at the 13th index:

const message = "I'm going now. Bye bye!"

console.log(message.endsWith("now", 13))

Output:

true

Just in case you don’t get it, here’s how the endsWith() method sees the problem when you gave it an index 13 as the second argument:

When only the first 13 characters count, the word indeed ends with “now”.

String.toUpperCase()

The toUpperCase() method returns an upper-case version of the original string.

String.toUpperCase()

For example, let’s convert this message to the upper case:

const message = "I'm going now. Bye bye!"
const upper = message.toUpperCase()

console.log(upper)

Output:

I'M GOING NOW. BYE BYE!

String.toLowerCase()

The toLowerCase() method returns a lower-case version of the original string.

String.toLowerCase()

For example, let’s convert this message to lowercase:

const message = "I'm GOING now. Bye BYE!"
const lower = message.toLowerCase()

console.log(lower)

Output:

i'm going now. bye bye!

String.includes()

In JavaScript, the includes() method checks if a specific substring exists in a string.

String.substring(searchString)

For example, let’s check if there is a substring “allow” in the word “shallow”:

const word = "shallow"
console.log(word.includes("allow"))

Output:

true

The includes() method also supports another optional argument. This argument is the index after which you want to check if a substring exists.

Let’s check if the word “allow” is present in the word “shallow” after index 3:

const word = "shallow"
console.log(word.includes("allow", 3))

Output:

false

The answer is obviously false, because the word “shallow” is “llow” when started at index 3.

But if you check if the word “shallow” has the word “low” after the 3rd index:

const word = "shallow"
console.log(word.includes("low", 3))

The answer is true:

true

String.repeat()

The repeat() method repeats a string a desired number of times. The method returns a new string that repeats the old one.

Here is the generic syntax of calling the repeat() method:

String.repeat(nTimes)

For example, let’s repeat the word “test” for five times:

const word = "test"
console.log(word.repeat(5))

Output:

testtesttesttesttest

String.charAt()

The charAt() method checks what is the character in a string at a given index.

Here’s the generic syntax for calling the method:

String.charAt(index)

For example, let’s check the character at the index number 3 (i.e. position 4) in the word “test”.

const word = "test"
console.log(word.charAt(3))

Output:

t

String.charCodeAt()

The charCodeAt() method returns the UTF-16 code (an integer between 0 and 65535) at the given index of a string.

Here’s the generic syntax for calling the method:

String.charCodeAt(index)

For instance, let’s check what’s the coding of the fourth letter in a string “test”:

const word = "test"
console.log(word.charCodeAt(3))

Output:

116

The reason why the resulting number is 116 boils down to the Unicode encoding of characters. A computer doesn’t understand characters as is. Instead, they’re represented as numbers behind the scenes.

In case you’re interested, here are the Unicode character encodings of the English alphabet:

UnicodeCharacterUnicodeCharacterUnicodeCharacterUnicodeCharacter
64@80P96`112p
65A81Q97a113q
66B82R98b114r
67C83S99c115s
68D84T100d116t
69E85U101e117u
70F86V102f118v
71G87W103g119w
72H88X104h120x
73I89Y105i121y
74J90Z106j122z
75K91[107k123{
76L92\108l124|
77M93]109m125}
78N94^110n126~
79O95_111o

Similarly, any other non-numeric characters must be represented as numbers behind the scenes.

For instance, JavaScript doesn’t understand what’s Emoji. This is why each Emoji also has a unique number associated with it.

String.fromCharCode()

The fromCharCode() method converts a UTF-16 code to a character. It does the exact opposite of the charCodeAt() method introduced earlier.

Here’s the generic syntax for calling the method:

String.fromCharCode(num)

For example, let’s take the number 116 and convert it to the corresponding string value:

console.log(String.fromCharCode(116))

Output:

t

Notice that you can pass any number of UTF-16 codes (i.e. numbers) to the fromCharCode() method. Here’s another example that showcases it:

console.log(String.fromCharCode(65, 66, 67))

Output:

ABC

String.substring()

The substring() method checks what substring starts at a given index.

Here’s the generic syntax for calling the method:

String.substring(startIndex)

For instance, let’s check what substring occurs at index 2 of the word “Shallow”:

const word = "Shallow"
const substr = word.substring(2)

console.log(substr)

Output:

allow

As you can see, the method checks what’s the “rest of the string” after a given index.

The substring() method takes another optional parameter. This limits the right end of the substring. For example, let’s see what’s the substring in the word “Shallow” after character number 2 to the character at position 5:

const word = "Shallow"
const substr = word.substring(2, 5)

console.log(substr)

Output:

all

String.padStart()

The padStart() method adds blank spaces to the beginning of a string. It takes the target length of the result string as an argument.

Notice that the target length is the desired end length of the padded string, not the number of padded blank spaces added.

So for example, if you add a string of 10 characters to 12, the method adds 2 blank spaces to the string. If you do the same for a string of length 5 the padStart() method adds 7 blank spaces to the result.

Here’s the generic syntax:

String.padStart(targetLength)

Let’s see an example of padding a string “test” to length 10:

console.log("test".padStart(10))

Output:

      test

Now the length of the result is the blank spaces combined with the original characters of the string.

The padStart() method takes a second optional argument. This argument specifies the padded string. By default, it’s a blank space. But you can change it to something else, such as a dash:

console.log("test".padStart(10, "-"))

Output:

------test

String.padEnd()

The padEnd() method adds blank spaces to the end of a string until a target length is reached.

This method works exactly like the padStart() method, except for adding blank spaces (and other strings) to the end of the string.

Here’s the generic syntax for calling the method:

String.padEnd(targetLength)

For example, let’s pad the word “test” to be 10 in length and use dashes as the fill-in values:

console.log("test".padEnd(10, "-"))

Output:

test------

String.codePointAt()

The codePointAt() method returns the Unicode value of a particular character of a string.

Here’s the generic syntax:

String.codePointAt(position)

For example, let’s get the codepoint of the first character of a string “test”:

console.log("test".codePointAt(0))

Output:

116

As you can see, the result is 116, which you saw earlier when using the charCodeAt() method. The charCodeAt() and codePointAt() methods are very similar:

  • The charCodeAt() returns the UTF-16 code unit of a character.
  • The codePointAt() returns the Unicode value of a character.

In other words, these methods return the same values for all the UTF-16 characters as long as they can be represented with a single UTF-16 unit. If the value overshoots the UTF-16 range, the methods return different values respectively.

String.fromCodePoint()

The fromCodePoint() method turns a Unicode point into a string.

Here’s the generic syntax:

String.fromCodePoint(codePoint)

This function can take as many codepoint arguments as you like.

For example, let’s convert the three integers 65, 66, and 67 to codepoints:

console.log(String.fromCodePoint(65, 66, 67))

Output:

ABC

String.match()

The match() method is a pattern-matching method that checks for each matching string inside a string.

The use of this method is much more sophisticated than it sounds. For example, you can use the match() method to find all emails from a text document using regular expressions.

Here’s the generic syntax:

String.match(regexp)

Notice that you need to pass a regular expression (regexp) as an argument to the method. If you’re unfamiliar with regex, make sure to read this first to understand the examples.

Let’s see a basic use case for the match() method. For example, let’s find all numbers from a string:

const str = "I got 3 apples, you got 5 apples, and Sam got 12 apples."
const re = /\d/g
const foundNumbers = str.match(re)

console.log(foundNumbers)

Output:

[ '3', '5', '1', '2' ]

The result is an array of strings where each string is a number that the match() method found in the string.

String.matchAll()

The matchAll() method returns all the results that match against a regular expression. The data type of the result is an iterator.

This method is very similar to the match() method. The key difference is that the match() method doesn’t return regex capturing groups which matchAll() does.

Here’s the generic syntax for using the method:

String.matchAll(regexp)

For example, let’s match against all the numbers in a string:

const str = "I got 3 apples, you got 5 apples, and Sam got 12 apples."
const re = /\d/g
const foundNumbers = str.matchAll(re)

console.log(foundNumbers)

for (num of foundNumbers) {
    console.log(num)
}

Output:

['3', index: 6, input: 'I got 3 apples, you got 5 apples, and Sam got 12 apples.', groups: undefined]

['5', index: 24, input: 'I got 3 apples, you got 5 apples, and Sam got 12 apples.', groups: undefined]

['1', index: 46, input: 'I got 3 apples, you got 5 apples, and Sam got 12 apples.', groups: undefined]

['2', index: 47, input: 'I got 3 apples, you got 5 apples, and Sam got 12 apples.', groups: undefined]

String.localeCompare()

The localeCompare() method checks the order of two strings.

Here’s the basic syntax of the method:

String.localeCompare(compareStr)

This method returns an integer that is negative if the string on which the method is called comes first.

The method returns a positive integer if the argument string comes first.

For example, here are two comparisons of strings in alphabetic order:

console.log("a".localeCompare("b"))
console.log("d".localeCompare("a"))

Output:

-1
1

The search() method finds the index of the first occurrence of a string matched against a regular expression.

Here’s the generic syntax for calling the method:

String.search(regexp)

For instance, let’s find the index at which the first number occurs on a string:

const str = "I got 3 apples, you got 5 apples, and Sam got 12 apples."
console.log(str.search(/\d/g))

Output:

6

The result is 6, which means that the 7th character is the first number in the example string.

String.replaceAll()

The replaceAll() method replaces all occurrences of a particular string (or pattern) in a string.

Here’s the generic syntax for calling the method:

String.replaceAll(pattern, replacement)

For example, let’s replace the word “apples” with “bananas”:

const str = "I got 3 apples, you got 5 apples, and Sam got 12 apples."
console.log(str.replaceAll("apples", "bananas"))

Output:

I got 3 bananas, you got 5 bananas, and Sam got 12 bananas.

Notice that you can also use regex to find matches to replace. For example, you could replace all numbers with something else.

String.concat()

The concat() method combines two strings and returns the combined string as a result.

Here’s the generic syntax for calling the method:

str1.concat(str2)

For example, let’s combine two strings to form a new one:

const w1 = "my "
const w2 = "house"

console.log(w1.concat(w2))

Output:

my house

String.split()

The split() method splits a string based on a separator. It returns the parts in an array of strings.

Here’s the generic syntax for calling the split() method:

String.split(separator)

For example, let’s split a string based on dashes:

const message = "my-car-looks-cool"
parts = message.split("-")

for (word of parts) {
    console.log(word)
}

Output:

my
car
looks
cool

Make sure to read my complete guide to using the split() method.

String.trim()

The trim() method removes all blank spaces from both ends of a string. These include tabs and multiple blank spaces.

Here’s the generic syntax for calling the method:

String.trim()

For example, let’s remove all the blank spaces from the start and the end of this sample string:

const message = "       my car looks cool     "
const trimmed = message.trim()

console.log(trimmed)

Output:

my car looks cool
javascript string trim() method cuts white spaces from the ends

String.slice()

The slice() method takes a section out of a string and returns the section.

Here’s the generic syntax for calling the method:

String.slice(startIndex)

For example, let’s leave out the first 11 letters of a string:

const message = "This is my message to you"
const part = message.slice(10)

console.log(part)

Output:

message to you

Wrap Up

That’s a whole bunch of string methods. Even though there are many methods you rarely need, there are certainly those you need every day.

I hope you found some useful ones that you will adapt to your programming routine!

Thanks for reading! Happy coding!

Read Also