JavaScript String Functions: Methods, Examples, and Uses

Formulas & functions · Updated November 22, 2026

JavaScript string functions are built-in methods and properties for working with text: finding words, extracting parts, changing letter case, replacing content, and more. Most are called on a string, such as 'hello'.toUpperCase(), and return a new string because JavaScript strings are immutable.

What JavaScript string functions are

In everyday conversation, “string functions” usually means the methods available on JavaScript strings. Technically, many are methods rather than standalone functions: they are called with dot notation on a string value. For example, 'JavaScript'.includes('Script') returns true. The length property is useful too, but it is a property, not a method, so it has no parentheses: 'cat'.length returns 3.

Strings represent text and can be written with single quotes, double quotes, or backticks. The quote styles are interchangeable for ordinary string literals, while backticks also allow interpolation and multiline text. For instance, `Hello, ${name}!` inserts the value of name into the resulting string.

JavaScript also has a global String object with static methods, including String.fromCharCode() and String.fromCodePoint(). These are different from methods called on a string value. For most day-to-day text processing, you will use instance methods such as trim(), slice(), and replace().

How to create and convert strings

A string literal is usually the clearest way to create text. When a value of another type needs to become text, use String(value) for explicit conversion. For example, String(42) produces '42', and String(true) produces 'true'. Conversion is often preferable to relying on implicit coercion, where JavaScript changes a value’s type as part of another operation.

Concatenation joins strings with the + operator, while a template literal is often easier to read when inserting values:

  • 'Order ' + orderId joins two pieces of text.
  • `Order ${orderId}` interpolates a value into a template literal.
  • String(null) explicitly produces the text 'null'; it does not produce an empty string.

That last distinction matters when displaying optional data. If a variable may be null or undefined, decide what the interface should show rather than assuming conversion removes it. A fallback expression such as value ?? '' uses an empty string only when the value is nullish.

Check length, characters, and positions

The length property reports a string’s number of UTF-16 code units, not necessarily the number of user-perceived characters. For basic English text, those counts usually match. For some emoji and other Unicode characters, they do not. This distinction becomes important when validating a visible character limit or moving through text by index.

To find text, use includes(), startsWith(), or endsWith(). These methods return booleans and are convenient for checks such as whether a filename has a particular suffix. indexOf() returns the position of the first match, or -1 when there is no match. Positions are zero-based, so a match at the beginning of a string is at index 0.

For example, 'green tea'.indexOf('tea') returns 6, while 'green tea'.includes('coffee') returns false. Do not test an indexOf() result just for truthiness: index zero is a valid match but is falsy. Compare with -1, or use includes() when only a yes-or-no answer is needed.

The charAt(index) method returns the code unit at a position as a one-character string, while bracket notation such as text[index] is another common way to access it. charCodeAt() returns a numeric UTF-16 code unit. These tools are useful for low-level text work, but they do not always correspond to a complete visible character.

Extract parts of a string

slice(start, end) returns a portion of a string from the start index up to, but not including, the end index. Omitting the end takes the remainder of the string. Negative indexes count back from the end, which makes slice(-4) a concise way to get the last four code units. The original string is not changed.

For example, 'JavaScript'.slice(0, 4) returns 'Java', and 'JavaScript'.slice(-6) returns 'Script'. The related substring(start, end) also extracts a range, but treats negative arguments as zero and swaps the arguments if the first is greater than the second. Those differences can make slice() easier to reason about when indexes might be negative.

You may encounter substr() in older code. It takes a start position and a length, but it is deprecated and should generally be avoided in new code. Use slice() with a calculated end position instead. If you want to split text into pieces, use split(separator): 'red,blue'.split(',') returns an array containing 'red' and 'blue'. Splitting on an empty string divides by UTF-16 code units, so it is not a safe general method for separating visible Unicode characters.

Change, clean, and format text

To change letter case, use toUpperCase() or toLowerCase(). These methods return new strings. They are useful for display and for simple case-insensitive comparisons, but language-specific casing rules can differ. For text intended for a particular language, toLocaleUpperCase() and toLocaleLowerCase() allow locale-sensitive behavior.

trim() removes whitespace from both ends of a string; trimStart() and trimEnd() target one side. They do not remove whitespace between words. For example, ' blue sky '.trim() returns 'blue sky', leaving the internal space intact. Trimming is commonly useful when accepting form input, though it should only be done when leading or trailing spaces are not meaningful for that data.

Use replace(searchValue, replacement) to replace the first matching string when the search value is plain text. If the search value is a regular expression with the global flag, it can replace every match. replaceAll(searchValue, replacement) replaces all occurrences of a string search value, or all matches when given a global regular expression. For example, 'a-b-a'.replaceAll('a', 'x') returns 'x-b-x'.

Padding methods can make text a minimum length: padStart(targetLength, padString) adds content at the beginning, and padEnd() adds it at the end. For example, '7'.padStart(3, '0') returns '007'. The target length is a minimum, not a maximum; padding does not truncate a longer input.

Search with regular expressions and split text

When a plain substring is not enough, JavaScript’s regular-expression methods provide pattern matching. match() returns match information, or null if there is no match. With a global regular expression, it returns an array of all matched text rather than one detailed match result. search() returns the index of the first match or -1. For repeated matches with capture groups, matchAll() returns an iterator and requires a regular expression with the global flag.

Regular expressions are powerful for patterns such as runs of digits, but they can be harder to read than literal string methods. If the task is simply checking whether text contains a known word, includes() is clearer. If a search string comes from a user and should be treated literally, be careful about inserting it directly into a regular expression: characters such as a dot or asterisk have special pattern meanings.

After split() makes an array, join(separator) combines array elements into a string. For instance, ['red', 'blue'].join(' / ') returns 'red / blue'. This is a common way to format a list or rebuild text with a chosen separator. Remember that split() returns an array, not another string.

Unicode and visible characters

JavaScript strings use UTF-16 encoding. Many familiar characters fit in one code unit, but some characters—including many emoji—are represented by a pair. As a result, '😀'.length is 2, and slicing at arbitrary indexes can split a surrogate pair. A code point-aware method such as codePointAt() can read a full Unicode code point, and String.fromCodePoint() can construct text from code points.

Even code points are not always the same as what a person perceives as one character. A visible symbol can be made from multiple code points, such as a base letter followed by a combining accent, or an emoji sequence joined with a zero-width joiner. For applications that must count or move across user-perceived characters, consider Intl.Segmenter with grapheme segmentation where the required browser environment supports it. Its availability depends on the JavaScript runtime, so check the target environments.

This is why length is appropriate for many programming tasks but should not automatically be treated as a user-facing character count. If a product requirement says “limit input to 20 characters,” clarify whether that means code units, code points, grapheme clusters, or a specific storage limit. The right interpretation depends on the application and its users.

Choosing the right method and avoiding mistakes

Start by describing the desired result: a boolean check, an index, a new string, or an array of pieces. Then choose the narrowest method that expresses it. For example, use startsWith() for a prefix check, slice() for a substring, and replaceAll() when every literal occurrence must change. Clear intent reduces surprises for people reading the code later.

  • Use includes() for a simple contains check, not indexOf() unless the position is needed.
  • Use slice() for extraction when negative indexes are useful or predictable behavior matters.
  • Use trim() to clean outer whitespace, not to collapse spaces throughout a sentence.
  • Use regular expressions when the match is a pattern; use literal methods for plain text.
  • Use localeCompare() when ordering text according to language-sensitive rules matters; direct relational comparisons are not a substitute for every human sorting rule.

A frequent misconception is that string methods modify the value in place. They do not: strings are immutable, so a transformation returns a result that must be stored or used. For example, calling text.trim() without assigning or otherwise using its return value leaves text unchanged. Another common mistake is confusing a method with a property: write text.length, not text.length().

Case conversion and trimming also do not automatically make text safe for every purpose. HTML output, SQL queries, URLs, and shell commands have different rules and risks. A string method alone is not a universal security measure; use the appropriate escaping, parameterization, or validation approach for the destination.

Frequently Asked Questions

What is the most commonly used JavaScript string method?
There is no single best method for every task. Common choices include includes() for checking text, slice() for extracting it, trim() for removing outer whitespace, and replace() for substitutions.

How do I check whether a string contains a word?
Use text.includes('word'). It returns true when that exact sequence appears and false otherwise. The comparison is case-sensitive, so convert both strings to a suitable case first if that matches your requirements.

Does replace() change every occurrence?
Not when its search value is a plain string: replace() changes the first occurrence. Use replaceAll() for every literal occurrence, or use a global regular expression with replace().

How can I reverse a JavaScript string?
For basic text, text.split('').reverse().join('') is a familiar approach, but it can break surrogate pairs and complex emoji sequences. For Unicode-aware reversal, first segment the text into grapheme clusters, then reverse those segments rather than individual UTF-16 code units.

Are JavaScript strings mutable?
No. A string method returns a new value instead of changing the original string. Assign the result to a variable or use it directly, for example const cleaned = input.trim().

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.