JavaScript has over 30 built-in string methods and properties, including length, toUpperCase(), toLowerCase(), indexOf(), slice(), substring(), substr(), replace(), split(), trim(), includes(), startsWith(), endsWith(), charAt(), charCodeAt(), concat(), repeat(), padStart(), padEnd(), match(), search(), localeCompare(), normalize(), and more. This article lists them all, explains what each does, and shows practical examples.
What Are String Methods and Properties?
Strings in JavaScript are primitive values, but the language wraps them in a String object when you call a method. This gives you access to a set of functions (methods) that operate on the text. The only property is length, which returns the number of UTF-16 code units (roughly characters) in the string.
Example: "hello".length returns 5. Note that emojis and some special characters take two code units, so "π".length returns 2.
Complete List of String Methods (Alphabetical)
charAt(index)β returns the character at the given index (0-based).charCodeAt(index)β returns the UTF-16 code unit (number) at the index.codePointAt(index)β returns the full Unicode code point (handles emojis).concat(str1, str2, ...)β joins strings; same as using+.endsWith(searchString, length?)β checks if the string ends with the given substring.includes(searchString, position?)β checks if the substring exists anywhere.indexOf(searchString, position?)β returns the first index of the substring, or -1 if not found.lastIndexOf(searchString, position?)β returns the last index of the substring.localeCompare(compareString)β compares two strings according to locale rules (returns negative, zero, or positive).match(regexp)β returns array of matches (or null).matchAll(regexp)β returns iterator of all matches (requires global regex).normalize(form?)β returns Unicode normalization form (NFC, NFD, etc.).padEnd(targetLength, padString?)β pads the end with a string to reach target length.padStart(targetLength, padString?)β pads the start.repeat(count)β repeats the string count times.replace(searchValue, replaceValue)β replaces first match (or all if regex with /g).replaceAll(searchValue, replaceValue)β replaces all occurrences (ES2021).search(regexp)β returns index of first match with a regex.slice(beginIndex, endIndex?)β extracts a section; supports negative indices.split(separator, limit?)β splits into an array of substrings.startsWith(searchString, position?)β checks if the string starts with the substring.substring(indexStart, indexEnd?)β extracts characters between two indices (no negatives).substr(start, length?)β deprecated, but still works; extracts length characters from start.toLocaleLowerCase()β converts to lowercase respecting locale.toLocaleUpperCase()β converts to uppercase respecting locale.toLowerCase()β converts to lowercase.toString()β returns the string itself.toUpperCase()β converts to uppercase.trim()β removes whitespace from both ends.trimEnd()/trimStart()β remove whitespace from end/start only.valueOf()β returns the primitive string value.
How to Choose the Right Method
Picking the right method depends on what you need:
- Searching: Use
includes()for a simple true/false,indexOf()for the position,search()for regex-based position. - Extracting: Use
slice()when you need negative indices (e.g., last 4 chars:str.slice(-4)). Usesubstring()when you only have non-negative indices. Avoidsubstr()(deprecated). - Replacing: Use
replace()with a regex and /g flag for all occurrences, orreplaceAll()for a simple string. - Formatting: Use
padStart()to zero-pad numbers (e.g.,"5".padStart(2, "0")gives"05"). - Case conversion: Use
toLowerCase()/toUpperCase(); use locale variants for languages like Turkish.
Common Pitfalls and Misconceptions
Strings are immutable. Every method returns a new string; the original is unchanged. For example, let s = "hello"; s.toUpperCase(); does nothing unless you assign the result: s = s.toUpperCase();.
substring() vs slice(): They behave the same for positive indices, but slice() accepts negative numbers (counting from the end) and swaps arguments if start > end, while substring() treats negative numbers as 0. Example: "hello".slice(-3) returns "llo", but "hello".substring(-3) returns "hello" (because -3 becomes 0).
replace() only replaces the first occurrence when given a string. To replace all, use a global regex: "a-b-c".replace(/-/g, "_") gives "a_b_c". Or use replaceAll("-", "_").
Indexing and emojis: Methods like charAt() and slice() work on UTF-16 code units, so an emoji like π (which is two code units) counts as two indices. Use Array.from(str) or spread operator to iterate by code points.
Practical Examples of Common String Operations
Here are a few realistic snippets:
- Capitalize first letter:
let name = "john"; name = name[0].toUpperCase() + name.slice(1);β"John". - Check if email is valid (simple):
email.includes("@") && email.endsWith(".com"). - Extract domain from URL:
let url = "https://example.com/page"; url.split("/")[2]β"example.com". - Remove all whitespace:
str.replace(/\s+/g, ""). - Reverse a string:
str.split("").reverse().join(""). - Truncate text with ellipsis:
str.length > 100 ? str.slice(0, 97) + "..." : str.
Performance Considerations
Most string methods are fast, but there are a few things to keep in mind:
- Using
+orconcat()in a loop to build a large string is O(nΒ²) because strings are immutable. Use an array andjoin()instead. split()with a regex can be slower than with a string separator.- For repeated searches,
indexOf()is generally faster than regexsearch(). - Modern JavaScript engines are highly optimized; premature optimization is rarely needed.
Alternatives to Built-in Methods
If you need more advanced string manipulation, consider:
- Regular expressions for complex pattern matching (using
match(),replace(),search()). - Intl.Collator for locale-aware string comparison instead of
localeCompare()when sorting arrays. - TextEncoder/TextDecoder for converting between strings and binary data (e.g., UTF-8).
- Lodash or other utility libraries for convenience functions like
_.camelCase()or_.truncate().
Frequently Asked Questions
What is the difference between substring, substr, and slice?
substring(start, end) extracts from start to end (exclusive) and treats negative values as 0. slice(start, end) also extracts from start to end, but supports negative indices (counting from the end). substr(start, length) extracts a specific length starting at start; it is deprecated and should be avoided. For most cases, use slice().
How do I replace all occurrences of a string in JavaScript?
Use replaceAll() if your environment supports ES2021 (most modern browsers). Otherwise, use replace() with a global regular expression: str.replace(/old/g, "new"). Remember to escape special regex characters if the search string contains them.
Why does “π”.length return 2?
JavaScript strings are UTF-16 encoded. Emojis and many other symbols (like some CJK characters) are represented by two code units (a surrogate pair). The length property counts code units, not visual characters. To count actual Unicode characters, use Array.from(str).length or the spread operator.
Is there a way to check if a string contains a substring without case sensitivity?
Yes, convert both strings to the same case first: str.toLowerCase().includes(substr.toLowerCase()). This is a common pattern. For more complex locale-aware case folding, consider using toLocaleLowerCase().
What is the fastest way to reverse a string?
The simplest is str.split('').reverse().join(''), but it breaks with emojis. For a more robust version, use Array.from(str).reverse().join(''). For very long strings, a loop with string concatenation is slower; using an array is better. There is no built-in reverse method.
Does JavaScript have a trim() method to remove only spaces, not tabs?
trim() removes all whitespace characters (spaces, tabs, newlines, etc.) from both ends. If you need to remove only spaces, use a regex: str.replace(/^ +| +$/g, ''). But in practice, trim() is what you want for most user input.
Related
- How to Sum All Subtotals in Excel (3 Ways)
- Bukit Batok Printing Shop: Quick Guide & Top Picks
- Cmd Commands Shortcut Keys: The Full List
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel IF OR Formula: Combine Multiple Conditions EasilyTo use Excelβs IF with OR, put OR in IFβs logical-test position: Excel checks whether at least one…
- Excel IF Formula Returns 0? Show a Blank Cell InsteadIf an Excel formula returns 0 and you want the cell to look blank, wrap the calculation in…
- Excel Delete Every X Rows: Safe Methods and FormulasYes. In Microsoft Excel for Microsoft 365 on Windows, add a helper column to mark every xth data…
- Excel Formula to Create a List Based on CriteriaIn Microsoft 365 or Excel 2021, use the FILTER function to create a list from rows that meet…
- M Code Function Syntax: A Practical GuideM code function syntax follows the pattern FunctionName(argument1, argument2, ...), where each argument is separated by a comma…
- Find Month and Year From a Date in Excel with FormulasTo find a month and year from a date in Excel, enter =MONTH(A2) for the month number and…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.