JavaScript String Operations: Methods and Examples

How-to basics · Updated November 22, 2026

JavaScript string operations are the ways you create, inspect, search, extract, combine, and change text. Strings are immutable primitive values, so methods such as slice() and replace() return new strings rather than modifying the original; the right operation depends on whether you need a position, a substring, a transformation, or Unicode-aware text handling.

What JavaScript strings are

A string is a sequence of text represented in JavaScript with the primitive type string. You can check a value with typeof value, which returns 'string' for a string primitive. JavaScript also has a String object, but ordinary application code generally uses primitive strings instead. Calling new String('hello') creates an object, not the same kind of value as the primitive 'hello', and can produce surprising comparison results.

Strings are immutable: their individual characters cannot be reassigned in place. For example, let word = 'cat'; word[0] = 'b'; does not change word. To make a changed value, assign the result of an operation: word = 'b' + word.slice(1). The variable can be reassigned when declared with let, but the string value itself is not edited.

This matters when reading code that chains methods. In const label = input.trim().toLowerCase(), each method produces a string for the next operation, and input remains unchanged. The chain is convenient, but it does not mean the original text was modified.

Creating and combining strings

String literals can use single quotes, double quotes, or backticks. Single- and double-quoted strings are useful for fixed text; backticks create template literals, which can interpolate expressions and span multiple lines.

  • const greeting = 'Hello'; creates a fixed string.
  • const message = `Hello, ${name}!`; inserts the value of name.
  • const lines = `First line
    Second line`;
    contains a line break between the two lines.

The + operator joins strings. If one operand is a string, JavaScript converts the other operand to a string in many common expressions: 'Items: ' + 3 produces 'Items: 3'. This implicit conversion can be useful for quick output, but it can also hide type mistakes. For example, '5' + 2 produces '52', not 7.

Template literals often make mixed text and values easier to read: const summary = `Items: ${count}`;. For joining an array of text values with a separator, use join(), such as ['red', 'green', 'blue'].join(', '), which returns 'red, green, blue'. The string method concat() also combines strings, but +, template literals, and join() are usually clearer choices.

Reading characters and measuring length

Use square-bracket indexing, charAt(), or at() to read a position. For example, 'JavaScript'[0] and 'JavaScript'.charAt(0) both return 'J'. The at() method also accepts a negative index counted from the end: 'JavaScript'.at(-1) returns 't'. If an index is out of range, bracket access and at() return undefined, while charAt() returns an empty string.

The length property reports the number of UTF-16 code units, not necessarily the number of characters a person sees. For ordinary English letters, the values often appear to match. Some symbols, including many emoji, use two code units, so '😀'.length is 2. This distinction is important when setting character limits or moving through text by index.

When you need to process Unicode code points rather than UTF-16 code units, a string can be iterated with for...of or spread into an array: [...'A😀'] contains two code-point strings. That still does not always count visible characters accurately: a flag, a skin-tone emoji, or a letter combined with an accent can consist of multiple code points displayed as one grapheme. Use the internationalization API, such as Intl.Segmenter, when a task genuinely requires user-perceived character boundaries.

Searching and checking string content

Use includes() for a straightforward yes-or-no check: 'JavaScript'.includes('Script') returns true. The check is case-sensitive, so searching for 'script' in 'JavaScript' returns false. If a case-insensitive check is required, normalize both sides consistently, for example by calling toLowerCase() before comparing. Language-sensitive comparisons may need locale-aware methods instead.

Use startsWith() and endsWith() when the location is specifically the beginning or end. These are often clearer than manually comparing slices. The indexOf() method returns the first matching position, or -1 if there is no match; lastIndexOf() searches from the end. Remember that a match at the beginning has index 0, so checking if (text.indexOf('x')) is a bug: it treats a valid first-position match as false. Prefer text.includes('x') for a Boolean condition.

For patterns rather than fixed text, regular expressions offer more powerful searching. For example, /\d+/.test('Order 42') checks whether the text contains one or more digits. A regular expression may be appropriate for validating a simple pattern or finding repeated structures, but a pattern is not automatically a complete validator for complex formats such as email addresses or URLs.

Extracting and replacing text

slice(start, end) extracts a portion of a string, including the character at start but excluding the character at end. It accepts negative indexes counted from the end: 'JavaScript'.slice(0, 4) returns 'Java', and 'JavaScript'.slice(-6) returns 'Script'. If the end argument is omitted, the slice continues to the end.

substring(start, end) is another extraction method, but it handles negative arguments differently: it treats them as zero and swaps the arguments if the first is greater than the second. For most new code, slice() is a predictable default, especially when negative offsets are useful. Neither method changes the original string.

Use replace(searchValue, replacement) to replace a match. With a plain string search value, only the first occurrence is replaced: 'red red'.replace('red', 'blue') returns 'blue red'. Use replaceAll() for every occurrence of a fixed string, or a regular expression with the global g flag. For example, '2026-11-03'.replace(/-/g, '/') returns '2026/11/03'.

The replacement can be a string or a function. A callback is useful when the replacement depends on the matched text or captured groups. Be careful when inserting user-provided text into a regular expression: characters such as ., *, and ? have special meanings. If the intent is literal matching, escaping or avoiding a dynamically constructed regular expression prevents those characters from changing the pattern.

Changing case, whitespace, and formatting

trim() removes whitespace from both ends of a string; trimStart() and trimEnd() target one side. They do not remove spaces from the middle. For example, ' hello '.trim() returns 'hello', while the original retains its spaces. Trimming is helpful when accepting form input, but it should be a deliberate product decision: whitespace may be meaningful in passwords, code, or other exact text.

toUpperCase() and toLowerCase() convert case and return new strings. JavaScript also provides toLocaleUpperCase() and toLocaleLowerCase() for conversions that can depend on locale. Do not assume lowercasing is a universal substitute for correct language-aware sorting or comparison; use the appropriate locale-sensitive tools when language rules matter.

For display formatting, padStart() and padEnd() add text until the requested string length is reached. For example, '7'.padStart(3, '0') returns '007'. repeat() repeats a string a specified number of times, as in '-'.repeat(5). These methods can be handy for labels and simple text output, but numeric formatting should generally use number-formatting tools when decimals, currency, or locale-specific separators are involved.

Splitting strings and joining arrays

split(separator) divides a string into an array. For instance, 'apples,pears,plums'.split(',') returns ['apples', 'pears', 'plums']. A regular expression can be used as the separator when the delimiter varies. To split into UTF-16 code units, an empty-string separator is possible, but it can break apart surrogate pairs used by emoji; it is not a safe general method for iterating visible characters.

Splitting on a space is not always the same as splitting on arbitrary whitespace. If text may contain repeated spaces, tabs, or line breaks, a regular-expression separator such as /\s+/ can be more suitable. Consider trimming first if leading or trailing whitespace should not create empty entries. Also decide how empty fields should be treated: in comma-separated data, an empty field can carry meaning, so filtering empty strings indiscriminately may lose information.

After editing an array of pieces, join(separator) puts them back into a string. For example, ['apples', 'pears'].join(' and ') returns 'apples and pears'. In practice, a common sequence is to split a line into fields, transform selected values, then join them using the intended delimiter. For real CSV files, however, delimiters can appear inside quoted fields; a simple split(',') does not implement the CSV format and a proper parser is safer.

Unicode, comparison, and common pitfalls

Two strings that look identical can have different underlying Unicode sequences. For example, an accented letter may be represented as one precomposed code point or as a base letter followed by a combining accent. The normalize() method can convert text to a Unicode normalization form, commonly 'NFC', before comparison or storage when consistent representation matters. Normalization is not the same as removing accents, and it should be applied consistently to both values being compared.

Simple equality with === compares string contents as sequences of code units; it does not perform locale-aware sorting or canonical Unicode equivalence automatically. For language-aware ordering, localeCompare() can compare strings according to locale options. Its exact result is negative, zero, or positive to indicate order; code should not rely on a particular negative or positive number. For sorting arrays, pass a comparison function such as (a, b) => a.localeCompare(b).

Another frequent mistake is assuming that every value has a safe toString() method. Calling null.toString() or undefined.toString() throws an error. The global String(value) converts these values to the strings 'null' and 'undefined', while template interpolation also converts many values. Choose conversion deliberately: if missing data should stay missing, validate it rather than blindly turning it into text.

Choosing an operation and avoiding unsafe output

Match the method to the task instead of building complicated logic from indexes:

  • For a yes-or-no substring check, use includes(); for a prefix or suffix, use startsWith() or endsWith().
  • For a portion by position, use slice(); for text replacement, choose replace() or replaceAll() according to whether all matches are intended.
  • For tokenizing text, use split() only when the input format is simple enough for the chosen separator.
  • For Unicode-aware user-visible character boundaries, do not treat length or indexing as a count of displayed characters.

String operations also matter for security. A string that is safe as plain text is not automatically safe when inserted into HTML, a URL, a SQL query, or a shell command. Use the escaping or parameterization mechanism designed for the destination; concatenating untrusted text into code or markup can create injection vulnerabilities. In a browser, assign plain text with textContent when markup is not intended, rather than treating arbitrary input as HTML.

Frequently Asked Questions

Are JavaScript strings mutable?
No. String values are immutable. Methods such as replace() and toUpperCase() return new strings, so keep or assign the result if you need the changed text.

How do I check whether a string contains another string?
Use includes(), for example text.includes('error'). It is case-sensitive. Normalize case first if a case-insensitive check is appropriate.

What is the difference between slice() and substring()?
Both extract part of a string, but slice() supports negative offsets from the end. substring() treats negative values as zero and swaps its arguments when the start is greater than the end.

Why does an emoji count as two characters in JavaScript?
length counts UTF-16 code units, and many emoji use a surrogate pair of two code units. Some displayed emoji combine several code points, so use Intl.Segmenter when you need user-perceived character segmentation.

How can I replace every occurrence of a word?
For a literal string, use replaceAll(). You can also use replace() with a regular expression carrying the global g flag. A plain string passed to replace() changes only its first match.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

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

Spotted an error in this guide? Let us know.