On W3Schools, “string functions” usually means JavaScript string methods: operations such as searching, replacing, slicing, and changing the case of text. In JavaScript, most of these are methods called on a string, while length is a property; the exact functions differ if you are using another programming language.
What W3Schools Means by String Functions
W3Schools has tutorials and references for several programming languages, so there is no single set of string functions that applies everywhere. A search for “string functions W3Schools” often leads to its JavaScript String Methods reference. JavaScript is a common starting point, but Python, PHP, Java, and other languages have their own names and rules for similar operations. Check the language heading before copying an example.
A string is text represented as a sequence of characters, such as 'Hello, world!'. In JavaScript, a string method is called with dot notation after a string value. For example, 'hello'.toUpperCase() returns 'HELLO'. A method is a kind of function associated with a value. The distinction matters because some useful string features are not methods: text.length, for instance, reads a property and does not use parentheses.
These features are built into JavaScript, rather than being special W3Schools commands. W3Schools provides explanations and examples; the JavaScript runtime in a browser or another environment provides the actual behavior.
How to Call a String Method
Put a period between the string and the method name, then include parentheses when the method takes arguments. An argument supplies information such as a search term, a position, or replacement text. For example, if message contains 'Welcome home', then message.includes('home') evaluates to true.
Here is a short example that combines a few common operations:
const message = ' Welcome home ';
const cleaned = message.trim();
const heading = cleaned.toUpperCase();
console.log(heading); // WELCOME HOME
trim() returns a version without whitespace at either end, and toUpperCase() returns an uppercase version. Neither operation changes the original string. JavaScript strings are immutable: methods produce a result, and your code must store or use that result if it needs it later. For example, calling message.trim() without assigning the result leaves message unchanged.
When a string is stored in a variable, use the variable’s name before the period. You can also chain methods, as in message.trim().toLowerCase(). Chaining can be concise, but intermediate variables may make a longer sequence easier to read and debug.
Common JavaScript String Methods
The methods below cover many everyday text-processing tasks. They are not interchangeable: check what each one returns and whether it changes, searches, or extracts text.
toUpperCase()andtoLowerCase()return a case-converted string. They are useful for basic comparisons that should ignore case, though language-specific casing rules can be more complicated than changing English letters.includes(searchValue)answers whether a string contains the supplied text. It returns a Boolean,trueorfalse, rather than the matching text.indexOf(searchValue)returns the position of the first match, or-1when there is no match. A match at the beginning has index0, so check for-1rather than treating a result of zero as false.startsWith()andendsWith()check whether text appears at the beginning or end of a string. They also return Boolean values.slice(start, end)extracts part of a string. The start position is included and the end position is excluded; omitting the end extracts through the end of the string. Negative positions count backward from the end.replace(searchValue, replacement)returns a copy with a match replaced. With a plain string as the search value, it replaces the first occurrence. A regular expression with the global flag can replace multiple matches.replaceAll(searchValue, replacement)replaces all occurrences of a string search value. If the search value is a regular expression, JavaScript requires the global flag.split(separator)divides a string into an array at each separator. For example,'red,blue'.split(',')returns an array containing'red'and'blue'.trim(),trimStart(), andtrimEnd()remove whitespace from both ends, the start, or the end, respectively. They do not remove spaces between words.padStart(targetLength, padString)andpadEnd()add text to the beginning or end until the requested length is reached. They are often used to display values with a consistent width.
For example, with const code = '7';, code.padStart(3, '0') returns '007'. It does not convert the value to a number, and it does not change code. That distinction is useful when formatting identifiers that may contain leading zeroes.
Choosing Between Similar Methods
Choose a method based on whether you need a position, a yes-or-no answer, or a piece of text. Use indexOf() when you need the position of a match; use includes() when you only need to know whether it exists. Use startsWith() or endsWith() when the location is specifically the beginning or end.
For extraction, slice() is a clear general-purpose choice. substring(start, end) also extracts a range, but it treats negative positions as zero and swaps the two arguments if the start is greater than the end. Those differences can make a mistake harder to spot. You may see substr() in older examples, but it is deprecated and should generally be avoided in new code.
For replacement, decide whether you want just the first match or every match. A common surprise is that 'one one'.replace('one', 'two') returns 'two one', not 'two two'. Use replaceAll() for all literal matches, or an appropriate global regular expression when the pattern needs to match more than fixed text.
Strings, Characters, and Indexing
JavaScript string positions are zero-based: the first position is 0, the next is 1, and so on. You can read the number of UTF-16 code units with the length property, as in 'cat'.length, which is 3. You can access a position with bracket notation, such as 'cat'[0], or use methods such as charAt(0).
There is a Unicode detail behind those simple examples. JavaScript’s length and many indexing operations count UTF-16 code units, not necessarily the symbols a person perceives as individual characters. Some emoji use two code units, and a visible character can also be formed from multiple Unicode code points. Therefore, a string’s length may not equal the number of characters a reader sees.
The at() method can read a position and supports negative indexes, so 'cat'.at(-1) returns 't'. Like other basic indexing approaches, it does not solve every issue involving combined emoji or accented characters. If an application must count or manipulate user-perceived characters accurately, it needs Unicode-aware handling rather than assuming each visible symbol occupies one position.
Converting Values and Formatting Text
Sometimes the challenge is turning a non-string value into text. The global String(value) conversion works for values including numbers and Booleans: String(42) produces '42'. Calling value.toString() is another option for many values, but it fails if the value is null or undefined, because those values do not have a callable toString() method.
Template literals offer another convenient way to build strings. They use backticks and can insert expressions inside ${...}, for example:
const name = 'Mina';
const greeting = `Hello, ${name}!`;
The value of greeting is 'Hello, Mina!'. Template literals are a JavaScript syntax feature, not a string method. They are useful when combining variables with text, while methods such as trim() and replace() are useful for transforming existing strings.
Common Mistakes and Safe Use
- Expecting a method to edit a string: methods such as
replace()andtoLowerCase()return new values. Reassign or store the result when you need to keep it. - Confusing a property with a method: write
text.length, nottext.length(). The latter attempts to call a number like a function. - Forgetting that positions start at zero: the first character is at index
0, and a missingindexOf()search returns-1. - Assuming all replacements are global: a plain string passed to
replace()matches only the first occurrence. SelectreplaceAll()or a global regular expression if every match should change. - Assuming strings are numbers: text such as
'12'is not the same type as the number12. Convert deliberately before doing arithmetic.
String methods are not a substitute for security controls. If text from a user is inserted into a web page, do not assume that replace() or a homemade cleanup rule makes it safe. The correct handling depends on where the value goes: HTML text, an HTML attribute, a URL, and JavaScript code have different escaping requirements. Use the platform’s appropriate safe text APIs and avoid building executable code from untrusted input.
Using W3Schools Examples Effectively
W3Schools examples can be a practical way to learn the shape of a method, but test a copied example in the context of your own task. Ask what type of value it returns, whether it handles only one match, what happens when the search fails, and whether the result needs to be assigned. These questions catch many beginner errors before they become larger bugs.
Also check the language and environment. A JavaScript example will not necessarily work in Python just because both languages manipulate strings. If an example uses a newer feature, verify that the browser or JavaScript runtime you support provides it. For a method that has several similar alternatives, compare its behavior in the relevant language’s documentation rather than relying on a method name that looks familiar from another language.
Frequently Asked Questions
Are string functions and string methods the same thing?
People often use the terms loosely. In JavaScript, many common string operations are methods called on a string, such as text.trim(). A function can also accept a string as an argument, while length is a property rather than either kind of function call.
What is the most commonly used JavaScript string method?
There is no single best answer; it depends on the task. Methods such as includes(), slice(), replace(), split(), and trim() are common because they cover searching, extracting, replacing, dividing, and cleaning text.
How do I replace every occurrence of a word?
For a literal string, use replaceAll(search, replacement). Alternatively, use replace() with a regular expression that has the global flag. A plain string search passed to replace() changes only the first occurrence.
Does length count characters?
It counts UTF-16 code units. For simple English text, that often matches the visible character count, but emoji and some combined characters can occupy multiple code units. Do not rely on length as a universal count of what a person sees as characters.
Can string methods change the original string?
No. JavaScript strings are immutable, so string methods return results rather than altering the original value. Assign the result to a variable or use it directly if you want the transformed text.
Related
- Accounting Trial Balance Worksheet: How It Works
- Google Sheets SPLIT Function: How to Separate Text
- Oracle Split String Example: SQL Methods That Work
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- How to Filter Specific Dates in ExcelTo filter specific dates in Excel, select a cell in your data, choose Data > Filter, open the…
- VLOOKUP Across Sheets in Excel: Formula and TipsYes. If the value to look up is in A2 on an Orders sheet, and a Product List…
- VLOOKUP Errors in Excel: Causes, Checks, and FixesMost VLOOKUP errors come from a lookup value that does not match the first column of the search…
- Sort by a Given List in Excel: Custom Order SortingTo sort Excel data in the order of a list you specify, select the full table, choose Data…
- Excel INDIRECT Across Sheets: How to Reference Other TabsYes. Excel’s INDIRECT function can refer to a cell or range on another sheet when you build that…
- Cash Flow Formula in Excel: Examples and How to Use ItThe basic cash flow formula in Excel is cash inflows minus cash outflows. If inflows are in B2…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.