Back to Explore
GuideVibeFix editorialUpdated Nov 20, 2026

Cut, splice, and tidy text without doing it by hand: string methods, explained plainly

The search box never matches, the cut lands one character off, replace swaps only the first one. This guide follows MDN's String, split, and slice references: read-only strings, length and at, the four finders, case-insensitive comparison, slice vs substring, split's blind spots, replace vs replaceAll, trim and padding, and template literals.

Real photo: blue scissors resting on cut-out colorful paper alphabet letters

First, the boundaries. The site already has a beginner's guide to regular expressions, about how to write regex, and “Stop writing for loops by hand: array methods”, about how to filter, transform, and collect arrays. This guide covers neither. It covers one thing: what to do with a piece of text itself — look something up in it, cut a piece out of it, replace part of it, or join it together — using the methods that come with strings. The “Greenstone Cafe” below is the same fictional practice project as before: a small web tool that takes orders for a street-corner cafe. This time it is about its search box: customers type a dish name to find a dish, and the text on the menu has to be tidied up before it is compared. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. Everything about string syntax and behavior comes from three MDN reference pages — “String”, “String.prototype.split()”, and “String.prototype.slice()”. The sources are listed in this article's meta information and evidence record. The examples in the docs — “The quick brown fox jumps over the lazy dog.”, the twelve-month string, “Oh brave new world that has such people in it.” — are the docs' own examples, not real services. By the end of this guide you should be able to do three things: know which method to reach for when you see “find a piece of text” and which one when you see “cut a piece out”; know that strings cannot be changed and that every method returns a new string; and know to tidy text up before comparing it or splitting it apart.

Step 1: Strings are read-only — drop the idea of editing a character

The first lesson about string methods is not a method at all. It is a temperament: strings cannot be changed. MDN says it plainly at the start of the “String” page — strings are sequences of UTF-16 code units, and you can read them but not change them. There are two ways to get one character: the charAt method and bracket notation. “cat”.charAt(1) gives “a”, and “cat”[1] gives the same “a”. Both give the same result. But bracket notation has a trap: it looks like an array, so it invites you to change a character the way you would change an array element. In fact deleting or assigning a value to those positions quietly fails, because the properties involved are neither writable nor configurable. Every string method follows the same temperament: not one of them changes the original string. They all return a new string. toUpperCase does not turn the original string uppercase, replace does not swap a word inside the original string, and trim does not wipe the spaces off the original string — each hands you a new string, and the original stays where it was. The cafe's search box paid for this mistake: someone wrote input.trim(), assumed the text in the box was now clean, and then compared the original variable. The spaces were still there, and the menu never matched. The correct form catches the return value: const clean = input.trim(), and then clean is what gets compared. Remember the rule: string methods never change the original — catch the return value first.

Step 2: Measure before you cut — length, at, and charAt

Measuring first is the cheapest step there is. length is the most-used property of a string. It is read-only, and it tells you how long the string is. MDN's wording is that length reflects the length of the string, but the word “length” needs care: it counts UTF-16 code units, not the characters you see with your eyes. One smiley face “😄” looks like one character, but its length is 2, because in UTF-16 it takes two code units — a surrogate pair. Two methods take an index: charAt(index) and at(index). charAt only takes a positive index counted from the start, and gives an empty string when the index is out of range. at is the newer addition, and it accepts negative numbers: at(-1) is the last character, at(-2) the second from last. MDN's “String” page states it clearly: at returns the character — exactly one UTF-16 code unit — at the given index, and negative integers count back from the last character. The cafe's dish codes are four digits plus one letter, like “0123A”. Checking one means first asking whether length is 5, then taking the last letter with at(-1) — much more direct than counting from the front. Keep one more rule in mind: length counts code units, so never use it as a character count on a string that contains emoji. Getting a real character count takes another approach, which this guide does not go into.

Once you have measured, here are two “take the code” methods that are easy to confuse: charCodeAt and codePointAt. MDN's method table in the “String” page is clear: charCodeAt(index) returns the numeric value of the UTF-16 code unit at the given index, while codePointAt(index) returns the code point value of the UTF-16 encoded code point starting at the given position. The difference only shows up on surrogate pairs: for an ordinary character both give the same result, but for an emoji made of two code units, charCodeAt only gives you the numeric value of the first half of the pair, while codePointAt gives you the whole character's code point. Everyday business code rarely calls these two methods directly, but recognizing them when you read an error or someone else's code keeps you from mixing up “numeric value” and “character”. One more fact worth knowing: a string's iterator walks by code points. [... "😄"] splits out one whole emoji, not two lone surrogates — MDN's “String” page shows this plainly. The spread operator iterates by code points, which is a different thing from split("") splitting by code units.

Step 3: Finding things — includes, indexOf, startsWith, and endsWith

Finding things is the most common need, and MDN gives four methods with a clear division of labor. includes(searchString) answers one question only: is it in there, true or false. It fits inside an if. indexOf(searchValue) answers: where is it, returning the index of the first occurrence, or -1 if it is not found. It fits when you need the position as well as the answer. startsWith and endsWith answer: does it begin or end with this string, again true or false. All four are case-sensitive. “Latte” and “latte” are not the same thing. MDN's “String” page states the indexOf rule plainly: it returns the index of the first occurrence of the search value, or -1 if not found. So the old way to test “is it in there” was indexOf(...) !== -1, and the new way is includes(...) directly — the newer form reads better. The cafe's search box uses this set: when a customer types “latte”, includes first checks whether any dish contains “latte”, then indexOf locates it so that part can be highlighted. Dishes starting with “iced” are filtered with startsWith into the cold-drinks section, and dishes ending with “combo” are filtered with endsWith into the combo section. Remember the rule: includes when you only ask whether it is there, indexOf when you need the position, startsWith and endsWith for the beginning and the end — and all four are case-sensitive.

Step 4: Unify the case before comparing, then bring in localeCompare

The easiest place to trip when comparing strings is comparing before the case has been unified. MDN spends a whole section of the “String” page on this: all comparison operators, including === and ==, compare strings case-sensitively. The common fix is to convert both sides to the same case first — toUpperCase or toLowerCase, and the choice between them is mostly arbitrary. MDN's example is function areEqualCaseInsensitive(str1, str2) { return str1.toUpperCase() === str2.toUpperCase(); }, converting both sides to upper case before comparing. But this fix is not fully robust: the German lowercase letter ß and “ss” both become “SS” under toUpperCase, so two strings that should be unequal get judged equal; the Turkish letter ı compared with “I” under toLowerCase gets judged unequal, when in Turkish they should be equal — unless you specifically use toLocaleLowerCase("tr"). MDN's robust solution is the localeCompare method or the Intl.Collator API, with the sensitivity option set to “accent” or “base”: str1.localeCompare(str2, "en-US", { sensitivity: "accent" }) === 0 judges ß and “ss” unequal in German and ı and “I” equal in Turkish. localeCompare exists to sort strings in a locale-aware way, and it doubles as a case-insensitive equality test. The cafe learned this the hard way: the menu's English dish names mix upper and lower case, customers type all lower case, and a direct === never matches. The correct approach converts both sides with toLowerCase first, or simply uses localeCompare. Remember the rule: unify the case before comparing, and bring in localeCompare when more than one language is involved.

Step 5: Cutting a piece out — which of slice and substring will not trap you

Cutting a piece out is the easiest step to get backwards, because two methods look alike: slice and substring. MDN lists both in the “String” method table, and the dedicated slice page spells out the rules in the most detail: slice(indexStart) or slice(indexStart, indexEnd) extracts a section and returns a new string, and the character at indexEnd is not included. MDN's example is str.slice(4, 19), which cuts “quick brown fox” out of “The quick brown fox jumps over the lazy dog.”, and str.slice(31) cuts “the lazy dog.”. The advantage of slice is that it accepts negative numbers: slice(-4) cuts from the fourth character from the end to the end, giving “dog.”, and slice(-9, -5) gives “lazy”. There are five rules: if indexStart is past the end of the string, an empty string is returned; if indexStart is negative, the index is counted from the end of the string; if indexStart is omitted, undefined, or cannot be converted to a number, it is treated as 0; if indexEnd is omitted or undefined, or past the end, slice extracts to the end of the string; if indexEnd is negative, it is counted from the end; and if indexEnd ends up at or before indexStart after normalizing negatives, an empty string is returned. substring also cuts a piece out, but it does not accept negative numbers — negatives are treated as 0 — and it does not care which of the two arguments is larger; it swaps them for you. MDN's method table says substring returns a new string containing characters of the calling string from, or between, the specified index or indices. The cafe's dish code “0123A” takes its first four characters with slice(0, 4) and its last letter with slice(-1); from a customer's “latte-large-less-sugar” the first part comes out with slice(0, 5). Remember the rule: reach for slice first — negatives work and the rules are easy to remember; substring only shows up in old code, so do not use it in new code.

Step 6: Splitting into an array — the five blind spots of split

split turns a string into an array, and it has the most blind spots of any string method. MDN gives it a whole page of its own, and it is worth reading rule by rule. First, omitting the separator or passing undefined returns an array with a single element: the calling string itself. Second, an empty string "" as the separator splits by UTF-16 code units one by one. “cat”.split("") gives three letters, but “😄”.split("") splits one emoji into two lone surrogates — something the “String” page also warns about. Third, the limit parameter is a cap, not “keep this many pieces and glue the rest back together”: str.split(" ", 3) takes only the first three pieces, and the leftover text is not included in the array at all. MDN's example is "Hello World. How are you doing?" split on a space with limit 3, giving ["Hello", "World.", "How"]. Fourth, when the separator appears at the beginning or the end of the string, the split still happens, and an empty string appears at the first or last position of the returned array; when the separator does not occur in the string at all, the returned array contains one element consisting of the entire string. Fifth, an empty string with a non-empty separator returns [""], and only an empty string with an empty separator returns []. MDN's wording is that "".split("") is the only way to produce an empty array when a string is passed as separator and limit is not 0. There is one more special behavior for regex separators: when the separator is a regular expression with capturing groups, the captured groups are spliced into the output array. MDN's example is "Hello 1 word. Sentence number 2.".split(/(\d)/), giving ["Hello ", "1", " word. Sentence number ", "2", "."]. The cafe's example is typical: the month string “Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec” split on commas gives 12 months — that is MDN's own example from the docs. And when a customer orders several dishes, the order record joins them with semicolons into “latte;americano;cappuccino;” — splitting on the semicolon leaves an extra empty string at the end, and forgetting to handle it makes the dish count come out one too many. Remember the rule: before you split, ask whether the separator is present, whether the ends will produce empty strings, and whether limit will throw the rest away.

Step 7: Replacing the unwanted part — replace only swaps the first one

replace is the method beginners misunderstand most, because its name sounds like “replace them all”, and it does not. MDN's “String” method table is clear: replace replaces occurrences of searchFor using replaceWith. searchFor may be a string or a regular expression, and replaceWith may be a string or a function. replaceAll replaces all occurrences of searchFor using replaceWith. That is the whole difference: pass a string to replace and only the first occurrence is swapped; to swap them all, use replaceAll, or write searchFor as a regular expression with the global flag. In the cafe's order notes, a customer wrote “less sugar less sugar less sugar” and wanted it unified to “half sugar”. Using replace("less sugar", "half sugar") only changes the first one, leaving the other two in place, so the kitchen gets an order that is half right and half wrong. Changing it to replaceAll("less sugar", "half sugar") changes all of them. One more detail is worth remembering: when replace's searchFor is a string, it is not parsed as a regular expression — dots and stars in it are just ordinary characters. To use the power of regex, write searchFor as a regular expression. MDN's method table also notes that when replaceWith is a function, it receives more information and can decide what to swap in for each match. That is an advanced use this guide leaves for later, after the regex guide. Remember the rule: replace with a string swaps only the first occurrence — use replaceAll for all of them, and count afterwards to confirm nothing slipped through.

Step 8: Tidying the ends — trim, trimStart, trimEnd, padStart, and padEnd

Text that comes out of an input box often carries extra spaces, and trim exists to clean that up. MDN's “String” method table puts it briefly: trim trims whitespace from the beginning and end of the string, trimEnd trims whitespace from the end, and trimStart trims whitespace from the start. All three return a new string and leave the original alone. The cafe's search box hits this every day: a customer types “latte” with two extra spaces on either side, and without trimming it never matches the “latte” on the menu, so the search box innocently reports that there is no such dish. Trim first, then compare, and the problem disappears. In the same family but working in the opposite direction are padStart and padEnd: they do not remove, they fill in. padStart(targetLength) pads from the start and padEnd(targetLength) pads from the end, until the string reaches the target length. The padding defaults to a space, but another string can be given. The dish code “7” needs four characters to line up, so padStart(4, "0") makes it “0007”, and sorting by code stays in order. Dish names that have to line up in a row can be padded with padEnd using spaces, so they look tidy. Remember the rule: trim before comparing, and think about pad for display. Both return new strings, so do not forget to catch the return value.

Step 9: Joining it together — template literals and String() conversion

There are three common ways to join strings, and MDN's “String” page separates their temperaments clearly. The first is the template literal: wrap text in backticks and write ${expression} inside, and the expression is converted to text by the string coercion rules. MDN's example is `${a} is less than ${b}`, dropping variables straight into a sentence. The second is the String() function: String(value) converts by the same rules, with the advantage that it does not throw on null and undefined. String(null) gives "null" and String(undefined) gives "undefined", while null.toString() throws a TypeError, because you cannot access properties on null or undefined. MDN makes this comparison explicitly at the end of the “String” page: the String() function is a more reliable way of converting values to strings than calling the toString() method, because it works when used on null and undefined. The third way is the plus operator, "" + x, and MDN explicitly recommends against it: it coerces its operand to a primitive instead of a string, and for some objects it behaves entirely differently from normal string coercion. One more conversion rule is worth remembering: undefined turns into "undefined", null turns into "null", true turns into "true", numbers convert the same way as toString(10), and Symbols throw a TypeError — unless you use String(), which returns "Symbol(description)". The cafe's order confirmation page joins things this way: a template literal combines the dish name, the quantity, and the price into one line like “latte x 2, 36 yuan total”, mixing numbers and strings without trouble. Remember the rule: use template literals to build sentences, use String() to convert a value you are unsure about, and leave "" + x alone.

Step 10: Counting the mistakes — six kinds of error made up all of them

The chart below is a fictional tally: 150 string-handling mistakes in one month on the Greenstone Cafe order page, split into six causes. The numbers are invented to make the point, not a real record. The largest group treated a string like an array and tried to rewrite it: 34 mistakes, 22.7%, matching Step 1. Second, slice and substring arguments written the wrong way round: 28 mistakes, 18.7%, matching Step 5. Third, split used without handling the empty strings at the ends: 26 mistakes, 17.3%, matching Step 6. Fourth, replace used once and assumed to have replaced everything: 24 mistakes, 16.0%, matching Step 7. Fifth, comparing with === before unifying the case: 20 mistakes, 13.3%, matching Step 4. Sixth, forgetting trim so the comparison failed: 18 mistakes, 12.0%, matching Step 8. The six groups add up to 34 + 28 + 26 + 24 + 20 + 18 = 150, and the percentages add up to 22.7 + 18.7 + 17.3 + 16.0 + 13.3 + 12.0 = 100.0. The books balance. Read the chart for the pattern, not the ranking: the top two mistakes are both cases of “thinking a string is something else” — an array, or something you can edit freely. The other four are all “one step skipped” — skipping case unification, skipping empty strings, skipping the return value. Fix the mental model first, then fix the code.

Bar chart of the causes behind 150 string-handling mistakes in one month

Step 11: A checklist to run through after writing string code

One last checklist. Run through it after writing, it takes ten seconds. First, before changing a string, ask: did I catch the return value, and is the original still sitting there untouched. Second, before taking an index, ask: length counts code units, so am I treating it as a character count on a string with emoji in it; to take the last character, use at(-1). Third, before searching, ask: includes when I only ask whether it is there, indexOf when I need the position, startsWith and endsWith for the beginning and the end — and all four are case-sensitive. Fourth, before comparing, ask: did I unify the case on both sides, and did I bring in localeCompare for the multi-language case. Fifth, before cutting a piece out, ask: slice leaves the end index out, and negative numbers count back from the end; substring does not accept negatives, so do not use it in new code. Sixth, before splitting, ask: will the separator at the start or end produce empty strings, will limit throw the rest away, and what does an empty string split into. Seventh, before replacing, ask: replace with a string swaps only the first occurrence — use replaceAll to swap them all. Eighth, before comparing, ask: did I call trim, and are the spaces at the ends of the input gone. Ninth, before joining, ask: did I convert uncertain values with String(), and is the "" + x form still in there. When all nine pass, the string code is done. When one fails, go back and fix it — do not count on the tests to catch it by accident.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: a laptop, tablet, and phone on a wooden table showing the same green-leaf website, the phone view with navigation in one column, a potted plant nearby
Guide
Squashed on phones? Responsive layout and media queries, explained plainly

One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.

Mobile AppsDesign ExperienceFrontend Engineering
Real photo: a Casio scientific calculator on a wooden desk showing 123456789 + 987654321 = 1111111110, beside handwritten math notebooks, a pen, a mug, and a laptop edge
Guide
Don't let 0.1 + 0.2 break your bill: JavaScript numbers and Math, explained plainly

Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.

Tool TipsFrontend EngineeringAI Coding