JavaScript string functions are built-in methods and properties for reading, searching, changing, and dividing text. For example, 'hello'.toUpperCase() returns 'HELLO', while 'hello'.includes('ell') returns true; most string methods return a result without changing the original string.
What JavaScript strings are
A string is a sequence of text characters, written between single quotes, double quotes, or backticks. These forms create string values, but backticks also allow template literals, which can include expressions and span multiple lines. For example, `Hello, ${name}!` inserts the value of the variable name into the text.
JavaScript strings are primitive values. They have a length property and methods such as slice() and trim(). JavaScript lets you call these methods directly on a string value; the language temporarily provides access to the corresponding string operations. You do not normally need to create a String object with new String(). That produces an object rather than a primitive and can behave unexpectedly in comparisons and conditionals.
Strings are immutable: a method cannot edit the characters in the existing string. Instead, a method that changes or extracts text returns a new string. If you want to keep the result, assign it to a variable:
const greeting = ' hello ';
const cleaned = greeting.trim();
console.log(cleaned); // 'hello'
console.log(greeting); // ' hello '
Reading characters and measuring text
The length property reports a string’s length in UTF-16 code units. It is a property, not a function, so write text.length, not text.length(). For basic text made up of ordinary English letters, digits, and spaces, this usually matches the number of visible characters.
To get a character by its position, use bracket notation, such as text[0], or the charAt() method. Positions start at zero, so the first character is at index 0. An index outside the string returns undefined with bracket notation, while charAt() returns an empty string. For example, 'cat'[1] and 'cat'.charAt(1) both produce 'a'.
Use at() when a negative index is useful: 'cat'.at(-1) returns the final character, 't'. The same negative index does not work as a way to count backward with bracket notation. These options are handy for short strings, but character indexing needs care with emoji and some accented characters, as explained below.
Extracting part of a string
slice(start, end) returns part of a string from the start index up to, but not including, the end index. The end argument is optional. For example, 'JavaScript'.slice(0, 4) returns 'Java'. If the end is omitted, the result continues to the end of the string. Negative indexes count from the end, so 'JavaScript'.slice(-6) returns 'Script'.
substring(start, end) also extracts a section, but handles negative values differently: it treats them as zero and swaps the arguments if the first is greater than the second. Because these differences can be surprising, slice() is often the clearest default for ordinary extraction. The older substr() method uses a start index and a length; it is deprecated and should generally be avoided in new code.
Choose an extraction method based on the boundaries you need. If you know the start and end positions, use slice(). If you want the text before or after a known separator, newer methods such as split() or indexOf() followed by slice() can make the intention explicit.
Finding and checking text
Use includes(searchValue) to check whether a string contains a piece of text. It returns a Boolean, which makes it useful in conditions. 'rainy day'.includes('day') is true. The check is case-sensitive, so searching for 'Day' in the same string returns false.
For a position, use indexOf(), which returns the first matching index or -1 if the text is absent. lastIndexOf() searches from the end. A common mistake is treating an index result as a Boolean: index zero is a valid match but is falsy. Check explicitly for -1, as in text.indexOf('A') !== -1, or use text.includes('A') when you only need a yes-or-no answer.
startsWith() and endsWith() check the beginning and end of a string. They can help validate a simple prefix or suffix, such as checking whether a filename ends in '.csv'. These checks are case-sensitive and are not a complete way to validate file types or security-sensitive input: a filename can have misleading text, and actual content or server-side rules may matter.
For patterns rather than fixed text, JavaScript supports regular expressions through methods such as match(), matchAll(), search(), and replace(). For example, 'item42'.match(/\d+/) finds a sequence of digits. Regular expressions are powerful, but a simple string method is easier to understand when the task is just checking for a literal substring.
Changing case, whitespace, and text
toLowerCase() and toUpperCase() return a case-converted string. They are useful for comparisons where case should not matter, but they do not automatically make all language-specific comparisons equivalent. For user-facing language-sensitive casing, JavaScript also provides toLocaleLowerCase() and toLocaleUpperCase(), which can take a locale such as 'tr'. The right choice depends on whether the task is a simple technical comparison or language-aware presentation.
trim() removes whitespace from both ends of a string. trimStart() and trimEnd() remove it from only one side. They do not remove spaces from the middle: 'first last'.trim() still has the three internal spaces. If you need to change internal spacing, define that rule separately, perhaps with a regular expression, and consider whether collapsing spaces is appropriate for the data.
replace(searchValue, replacement) returns a copy with a match replaced. With a plain string search value, it replaces only the first occurrence. To replace every occurrence of a literal substring, use replaceAll(), or use a regular expression with the global flag when a pattern is needed. For example, 'a-a-a'.replaceAll('-', ':') returns 'a:a:a'. When replacement text includes user-provided values, do not assume a text replacement is automatically safe for HTML, SQL, or another output format; use the appropriate escaping or parameterized APIs.
Splitting and joining strings
split(separator) divides a string into an array. The separator can be a string or a regular expression. For example, 'red,green,blue'.split(',') returns ['red', 'green', 'blue']. An empty-string separator splits by UTF-16 code units, not necessarily by visible characters, so it is not a reliable way to divide every kind of Unicode text into user-perceived characters.
The optional limit argument caps how many array elements are returned. Separators are not included in the result when a string separator is used. Empty or repeated fields can matter: 'a,,b'.split(',') includes an empty element between the commas. If data is structured or may contain quoted separators, a simple split may not be enough; use a parser designed for that format, such as a CSV parser for CSV data.
To combine array elements into a string, use join(separator) on the array. For instance, ['red', 'green', 'blue'].join(' | ') returns 'red | green | blue'. Splitting and joining are often paired when transforming delimited text, but remember that the separator and escaping rules of the real data format determine whether this approach is safe and accurate.
Unicode, emoji, and character counts
A JavaScript string is represented as UTF-16 code units. That means length, bracket indexing, and several string operations count those units, not necessarily visible symbols. For example, many emoji use two code units, so '😊'.length is 2, even though a person sees one emoji. Some displayed characters combine multiple Unicode code points, such as a letter and a combining accent, and can take even more than one code unit.
When you need to iterate by Unicode code point, a string’s iterator can help: [...'😊'] creates an array with one element for this emoji. The for...of loop also iterates by code point. However, a visible grapheme can consist of multiple code points, such as a family emoji joined from several symbols. For reliable user-perceived character counting or cursor movement, use grapheme segmentation, available through Intl.Segmenter in supported modern environments, and check the browser or runtime support required by your application.
This distinction matters when limiting text length, positioning selections, or showing character counts in an interface. A limit based only on length may count emoji differently from what users expect. Decide whether your application’s rule concerns storage units, Unicode code points, or visible grapheme clusters, and use the matching approach.
How to choose the right string method
Start with the operation you actually need rather than selecting a method because its name sounds general. These common choices cover many everyday tasks:
- Check for text: use
includes(); check a prefix or suffix withstartsWith()orendsWith(). - Find a location: use
indexOf()orlastIndexOf(); usesearch()when the search is a regular expression. - Extract by position: use
slice(); usesplit()when the separator should divide the string into pieces. - Clean boundaries: use
trim(),trimStart(), ortrimEnd(). - Replace text: use
replace()for a first match,replaceAll()for every literal match, or a regular expression for a pattern. - Format values into text: use a template literal, such as
`Total: ${total}`.
For readable code, choose the method that communicates intent and handle the cases your data can actually contain. A one-line method call does not validate an entire input format, normalize every language’s text, or safely encode content for a different context.
Common mistakes and practical cautions
One frequent error is expecting a method to alter its source string. Since strings are immutable, text.trim() does not change text; store the returned value if it is needed later. Another is confusing properties with methods: use text.length, but use parentheses for methods such as text.toLowerCase().
Case-sensitive searching can also cause bugs when input comes from users. If the requirement is case-insensitive matching, decide how to normalize both values before comparing them, while remembering that simple lowercasing is not a universal substitute for locale-aware language rules. For identifiers defined by a technical standard, follow that standard rather than applying broad normalization without checking its requirements.
Finally, do not treat string methods as security controls by themselves. Removing a few characters or checking whether text contains a phrase is not a substitute for validating input according to its expected format. When inserting text into HTML, a URL, a shell command, or a database query, use context-appropriate APIs and escaping. The safe approach differs by destination, and string manipulation alone does not prevent injection vulnerabilities.
Frequently Asked Questions
What is the difference between a JavaScript string property and a method?length is a property accessed without parentheses, as in text.length. A method performs an operation and is called with parentheses, such as text.includes('x') or text.slice(1).
How do I check whether a string contains a word in JavaScript?
Use includes() for a literal, case-sensitive check: text.includes('word'). If matching should ignore case, define a consistent comparison rule for both the input and search term, and consider language-specific requirements.
Does replace() replace every match?
Not when its search value is a plain string: that form replaces the first occurrence. Use replaceAll() for every occurrence of a literal string, or a global regular expression for pattern-based replacement.
How can I remove spaces from a JavaScript string?
Use trim() to remove whitespace at the beginning and end. It leaves spaces between words unchanged. To remove or collapse internal whitespace, specify that transformation separately and make sure it suits the text’s purpose.
Why is the length of an emoji sometimes 2?
JavaScript’s length counts UTF-16 code units, and many emoji require two units. Visible characters can also be formed from multiple code points. Use Unicode-aware iteration or grapheme segmentation when the application needs to count user-perceived characters.
Related
- Can You Play Split Fiction Solo? What to Know
- SQL ENUM Example: Syntax, Uses, and Alternatives
- Hide Column Names in Power BI: What Actually Works
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- VLOOKUP to Compare Two Columns on Different SheetsYes. In Excel for Microsoft 365, use an exact-match VLOOKUP to check whether each value in one sheet’s…
- Snowflake String Functions: Examples and Practical UsesSnowflake string functions let you combine, inspect, extract, search, and transform text in SQL. For example, use CONCAT(first_name,…
- VLOOKUP With Multiple Criteria: Excel FormulasIf your table has Product in column B, Region in C, Sales in D, and a combined lookup…
- VLOOKUP Formula Examples in Excel: Exact and ApproximateIn Excel, VLOOKUP searches the first column of a range and returns a value from another column in…
- Excel Not Equal to Blank: Formulas, Examples, and FixesTo test whether a cell is not blank in Excel, use the not-equal operator with an empty string:…
- Basic IF Examples in Excel: How to Write the FormulaIn Excel, an IF formula checks whether a condition is true and returns one value if it is,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.