JavaScript String Methods: Beginner Guide to Text Manipulation with Real Examples

JavaScript String Methods: Beginner Guide to Text Manipulation with Real Examples

How to Slice, Clean, Pad, and Format Strings in Real-World Web Projects

Author
Nguyen Bao Huy
10:03:00 21/02/2026
4 min read
0 comments

The Golden Rule: Strings Never Change

When you manipulate a string in JavaScript, the original variable stays untouched unless you explicitly reassign it:

javascript
let website = "stackra";

website.toUpperCase();
console.log(website); // Still "stackra"!

// To save the result, reassign or store in a new variable:
website = website.toUpperCase();
console.log(website); // "STACKRA"

1. Checking Text Length: .length

The .length property tells you how many characters are inside a string.

Real-world scenario: Validating user passwords upon signup (e.g., minimum 8 characters).

javascript
let userPassword = "pass123";

if (userPassword.length < 8) {
  console.log("Password is too short. It must be at least 8 characters.");
} else {
  console.log("Password accepted!");
}
// Output: Password is too short. It must be at least 8 characters.

2. Picking Specific Characters: .at() vs .charAt()

When building user profile badges or parsing data, you often need the first or last character.

The Modern Approach: .at() (Recommended)

Introduced in ES2022, .at() lets you use negative numbers to count backward from the end:

javascript
const framework = "Next.js";

console.log(framework.at(0));  // "N" (first letter)
console.log(framework.at(1));  // "e" (second letter)
console.log(framework.at(-1)); // "s" (last letter)
console.log(framework.at(-2)); // "." (second to last)

The Traditional Approach: .charAt()

Older codebases use .charAt(). Note that it does not accept negative indices:

javascript
const name = "Stackra";

console.log(name.charAt(0));                 // "S"
console.log(name.charAt(name.length - 1));   // "a" (cumbersome way to get the last letter)

Getting Unicode Values: charCodeAt() & codePointAt()

If you need character codes for sorting algorithms or encryption:

javascript
let text = "HELLO";

// Gets 16-bit UTF-16 code (Good for basic English letters)
console.log(text.charCodeAt(0)); // 72 ("H")

// Gets full Unicode code point (Best for Emojis)
let rocket = "🚀";
console.log(rocket.codePointAt(0)); // 128640

3. Extracting Parts of Strings: slice() vs substring()

Need to grab only a portion of a string? Use extraction methods.

slice(start, end) (Your go-to extraction tool)

Extracts from start up to (but not including) end. Supports negative numbers to cut from the back:

javascript
let file = "banner-image.png";

// Grab the file extension:
let extension = file.slice(-3);
console.log(extension); // "png"

// Grab the filename without extension:
let fileNameOnly = file.slice(0, 12);
console.log(fileNameOnly); // "banner-image"

substring(start, end)

Similar to slice, but treats any negative number as 0 and swaps parameters if start > end:

javascript
let file = "banner-image.png";

// Grab the file extension:
let extension = file.slice(-3);
console.log(extension); // "png"

// Grab the filename without extension:
let fileNameOnly = file.slice(0, 12);
console.log(fileNameOnly); // "banner-image"
Avoid substr(start, length): This method is deprecated in modern JavaScript standards. Always use slice() instead.

4. Cleaning User Inputs: trim(), trimStart(), and trimEnd()

Users frequently add accidental spaces when filling out web forms. Always sanitize inputs before storing them in your database.

javascript
let emailInput = "   alex@example.com  \n";

// Remove spaces from both ends:
let cleanEmail = emailInput.trim();
console.log(cleanEmail); // "alex@example.com"

// Trim only the beginning:
console.log("   Welcome".trimStart()); // "Welcome"

// Trim only the end:
console.log("Welcome   ".trimEnd());   // "Welcome"

5. Changing Case: toUpperCase() & toLowerCase()

Used primarily to make string searches and comparisons case-insensitive.

javascript
let searchInput = "REACT";
let databaseCategory = "react";

// Case-insensitive comparison:
if (searchInput.toLowerCase() === databaseCategory.toLowerCase()) {
  console.log("Match found!");
}

6. Formatting & Masking: padStart(), padEnd(), and repeat()

padStart(targetLength, padString)

Pads the beginning of a string until it hits the target length.

Real-world scenario: Masking credit card numbers or order IDs.

javascript
// Example A: Mask a credit card (Show only the last 4 digits)
let fullCard = "1234567812348899";
let last4 = fullCard.slice(-4);
let maskedCard = last4.padStart(fullCard.length, "*");
console.log(maskedCard); // "************8899"

// Example B: Formatting numbers with leading zeros
let invoiceNumber = 42;
let formattedInvoice = String(invoiceNumber).padStart(5, "0");
console.log(formattedInvoice); // "00042"

padEnd(targetLength, padString)

Pads the end of a string to reach the target length:

javascript
let productCode = "SKU-";
console.log(productCode.padEnd(8, "0")); // "SKU-0000"

repeat(count)

Duplicates a string count times:

javascript
let starRating = "⭐".repeat(5);
console.log(starRating); // "⭐⭐⭐⭐⭐"

7. Combining Strings: concat() vs Modern Template Literals

While .concat() works, modern JavaScript uses Template Literals (${}) because they are cleaner and easier to read.

javascript
let firstName = "Nguyen";
let lastName = "Huy";

// Method A: .concat()
let fullNameConcat = firstName.concat(" ", lastName);

// Method B: Modern Template Literal (Best Practice)
let fullNameModern = `${firstName} ${lastName}`;
console.log(fullNameModern); // "Nguyen Huy"

8. Dealing with Emojis & Corrupted Text: isWellFormed() (ES2024)

When handling text uploads or user comments containing emojis, strings can sometimes get cut mid-character, creating corrupted "lone surrogates."

javascript
let goodText = "Hello World 🚀";
console.log(goodText.isWellFormed()); // true

let brokenText = "Broken emoji: \uD800"; // Cut halfway through
console.log(brokenText.isWellFormed()); // false

// Fix corrupted text automatically before sending to backend/API:
let safeText = brokenText.toWellFormed();
console.log(safeText); // "Broken emoji: "

Quick Cheat Sheet: JavaScript String Methods

MethodWhat It DoesBeginner Example
.lengthReturns character count"abc".length => 3
.at(i)Gets character at index (supports negatives)"cat".at(-1) => "t"
.slice(start, end)Cuts out a portion of text"Hello".slice(0, 2) => "He"
.trim()Removes leading and trailing whitespace" a ".trim() => "a"
.toLowerCase()Converts text to all lowercase"JS".toLowerCase() => "js"
.toUpperCase()Converts text to all uppercase"js".toUpperCase() => "JS"
.padStart(len, char)Pads front of string with characters"5".padStart(3, "0") => "005"
.repeat(n)Repeats string $n$ times"ha".repeat(3) => "hahaha"

Ready for the Next Step?

Now that you know how to slice, pad, and clean strings, the next fundamental skill is knowing how to search through them or inject variables dynamically.

💡 Building a Web Project?
Don't spend hours writing boilerplate code from scratch. Explore our free collection of developer resources and component templates in the Stackra Tools & Open Source Directory!
1 engineers appreciated this

First Lesson

You are at the beginning of this curriculum.

Latest Tutorial

More chapters coming soon to this topic.

Author avatar

Nguyen Bao Huy

Lead Fullstack & AI Solutions Engineer

Specializing in Next.js App Router, React 19, TypeScript, and modern design systems. Passionate about creating seamless user experiences.

Discussion

0

No comments yet

Be the first to share your thoughts, question a concept, or provide additional tips!

Leave a Reply

Share your insights, questions, or solutions with the developer community.

Your avatar
0 / 500 characters