Essential String Methods in Javascript: Trimming, Searching, Combining Text and Many more

Sangy KSangy K
8 min read

Table of contents

Let's be honest—real-world strings are messy.

User input often includes extra spaces, missing words, or unusual formatting.

Thankfully, Javascript gives us a toolbox 🧰 packed with string methods that make cleaning and combining text a breeze.

In this article, we'll walk through string manipulation step by step—from simple concatenation to powerful replacements—so we can craft clean, readable, and reliable text handling in our apps.

Ready? Let's go! 💨

String Concatenation: +, +=, and Why We Prefer Template Literals

The simplest way to combine strings is by using the + operator:

let firstName = "Luna";
let greeting = "Hello, " + firstName + "!";
console.log(greeting); // "Hello, Luna!"

Or we can use += to build strings over time:

let message = "Welcome ";
message += firstName;
message += "!";

console.log(message); // "Welcome Luna!"

⚠️ Pro Tip:

Be careful when mixing numbers and strings — Javascript loves to turn things into text when you use +.

console.log("5" + 2); // "52" — oops, that's a string, not math!

But Honestly? We Prefer Template Literals

Remember template literals from our earlier article? They make all this so much cleaner:

let greeting = Hello, ${firstName}!;
console.log(greeting); // "Hello, Luna!"

It's easier to read 🧼, no need for messy + signs 😵, and avoid type confusion 😕 (no accidental string-number mishaps).

🔠 Changing Case in Strings: Making Text Loud or Quiet

🎩 .toUpperCase(): Convert Everything to UPPERCASE

This turns all characters in a string to uppercase. Simple and solid.

let name = "Marco";
console.log(name.toUpperCase()); // "MARCO"

✔️ Perfect for displaying headings, constants, or usernames in a consistent style. Additionally, it can be used for case-insensitive comparisons (convert both values to uppercase before comparison).

🔡 .toLowerCase(): Convert to lowercase

This makes every character lowercase.

let message = "HELLO There!";
console.log(message.toLowerCase()); // "hello there!"

✔️ Perfect for normalising email addresses, usernames, or any user input before saving or comparing. Also, in case-insensitive searches, convert both values to lowercase before comparison.

⚠️ Note:

These two methods are essentials.

Safe to use almost everywhere unless you're working with non-English locales, where .toLocaleUpperCase() and .toLocaleLowerCase() handle edge cases better.

✂️ Removing Extra Spaces with .trim(), .trimStart(), and .trimEnd()

🧹.trim(): Clean Up Both Ends

.trim() removes all whitespace from the start and end of a string. Spaces, tabs, newlines—gone.

let input = " Hello World ";
console.log(input.trim()); // "Hello World"

✔️ Perfect for cleaning user input before saving it to a database or validating form fields.

↘️ .trimStart(): Remove Leading Spaces

Removes spaces only from the start (left side):

let input = " Hello";
console.log(input.trimStart()); // "Hello"

↗️ .trimEnd(): Remove Trailing Spaces

Removes spaces only from the end (right side):

let input = "Hello ";
console.log(input.trimEnd()); // "Hello"

⚠️ Note:

These are modern Javascript features (ES2019+), and all major browsers now support them.

Always use .trim() on form inputs—it's one of the easiest ways to avoid annoying bugs from invisible spaces.

🔍 Finding Text: .indexOf() and .lastIndexOf()

🎯 .indexOf(): Find the First Match

This searches the string and returns the index of the first occurrence of the search term. If it's not found, it returns -1.

let phrase = "hello world hello";
console.log(phrase.indexOf("hello")); // 0

➡️ Best for finding where something first appears.

🔙 .lastIndexOf(): Find the Last Match

Same as .indexOf(), but works backwards — finds the last occurrence.

console.log(phrase.lastIndexOf("hello")); // 12

⚠️ Note:

Both are case-sensitive. If you need a case-insensitive search, lowercase everything first.

These methods work, but can be clunky for simple checks — prefer .includes() when you just want to know if something exists.

🔎 Searching Made Simple: .includes(), .startsWith(), .endsWith()

🔍 .includes(): Does It Exist?

Returns true if the string contains the search text, false if not.

let sentence = "Hello, Luna!";
console.log(sentence.includes("Luna")); // true

Cleaner and more readable than the .indexOf() method.

🚀 .startsWith(): Check the Beginning

Returns true if the string starts with a certain substring.

console.log(sentence.startsWith("Hello")); // true

🏁 .endsWith(): Check the End

Returns true if the string ends with the given substring.

console.log(sentence.endsWith("!")); // true

These are the go-to search methods in modern Javascript.

They're clear, concise, and just work — no weird -1 comparisons like .indexOf().

✂️ Extracting Parts of a String: .slice(), .substring(), .substr()

✂️ .slice(): The Modern Favourite

Extracts part of a string, from a start index to an end index (non-inclusive).

let word = "Javascript";
console.log(word.slice(0, 4)); // "Java"

✔️ Allows negative numbers to count from the end:

console.log(word.slice(-6)); // "script"

This is the one we use most often — clean and flexible.

🔪 .substring(): The Older Cousin

Similar to .slice(), but doesn't accept negative indexes.

console.log(word.substring(0, 4)); // "Java"

Still works fine, but there's rarely a reason to pick this over .slice().

⚠️ .substr(): Deprecated

Extracts part of a string based on start position and length. Now considered outdated.

console.log(word.substr(0, 4)); // "Java"

📛 Avoid it — use .slice() instead.

✔️ In modern Javascript, we stick with .slice() for clarity and versatility.

🔄 Replacing Parts of a String: .replace() and .replaceAll()

🔁 .replace(): Swap the First Match

Replaces the first occurrence of a substring.

let message = "Hello Luna, Luna!";
console.log(message.replace("Luna", "SK")); // "Hello SK, Luna!"

If you need to replace only once, this is the tool for you.

🔁 .replaceAll(): Swap Everything

Replaces all occurrences of a substring.

console.log(message.replaceAll("Luna", "SK")); // "Hello SK, SK!"

ES2021 introduced this, making it way better than the old RegExp hacks.

✔️ Both work great with simple text.

If we need complex patterns, we pair .replace() with regular expressions (/pattern/g).

🪓 Splitting & Joining Strings: .split(), .join()

🔨 .split(): Break a String Into Pieces

Turns a string into an array based on a separator.

let sentence = "Buy milk, Do yoga, Write code";
let tasks = sentence.split(", ");
console.log(tasks); // ["Buy milk", "Do yoga", "Write code"]

The default behaviour splits wherever it finds the separator.

If the separator doesn't exist in the string, Javascript returns a one-item array containing the whole string.

🔗 .join(): Put It Back Together

Takes an array and joins it back into a string.

console.log(tasks.join(" | ")); // "Buy milk | Do yoga | Write code"

We use this a lot when formatting lists or generating CSV-like output.

✔️ Great for parsing CSV files, breaking sentences into words, or rebuilding text from array data.

🔁 Repeating & Padding Strings: .repeat(), .padStart(), .padEnd()

🔂 .repeat(): Copy the String Multiple Times

Repeats the string as many times as we want.

console.log("Hi! ".repeat(3)); // "Hi! Hi! Hi! "

Simple way to build patterns, repeated labels, or visual dividers.

⬅️ .padStart(): Add Padding to the Left

Adds characters to the beginning until the string reaches a certain length.

console.log("5".padStart(3, "0")); // "005"

➡️ .padEnd(): Add Padding to the Right

Pads the end of the string.

console.log("42".padEnd(5, "*")); // "42***"

✔️ Common use cases:

  • Formatting numbers with leading zeros.

  • Aligning text outputs.

  • Creating simple loading animations like ".", "..", "...".

🔧 Escaping Characters & Special Sequences

🛡️ Escaping Quotes Inside Strings

If we want quotes inside a string, we escape them using a backslash (\):

let quote = "She said, \"Hello!\"";
console.log(quote); // She said, "Hello!"

✔️ This lets us mix single and double quotes without breaking the syntax.

📂 Backslashes in Paths

The same goes for file paths in Windows:

let path = "C:\\Users\\Luna\\Documents";

🔤 Other Common Escape Sequences

SequenceMeaning
\nNewline
\tTab
\\Backslash
\'Single quote inside single-quoted string
\"Double quote inside double-quoted string

✔️ Essential when we're working with file paths, JSON, multiline text, or any string that needs special characters.

⚖️ Comparing Strings the Right Way

The Basic Way:

Javascript compares strings by Unicode value, so:

console.log("abc" === "abc"); // true
console.log("abc" < "bcd"); // true

⚠️ Weird case: Uppercase letters come before lowercase in Unicode:

console.log("Zebra" < "apple"); // true

🌍 For Locales: Use .localeCompare()

If we need language-sensitive comparisons (for example, sorting German or Turkish words), we use this:

console.log("straße".localeCompare("strasse")); // may be 0 or 1 depending on locale

✔️ Critical for apps that sort words in different languages correctly.

✔️ Best Practices for Working with Strings

  • Prefer template literals (${} inside backticks) over messy + concatenation — it's easier to read and avoids bugs.

  • Always trim user input before validating or saving it. Invisible spaces are sneaky bugs.

  • Use .includes() instead of .indexOf() > -1 — it reads like plain English.

  • Don't use deprecated methods like .substr().

  • Avoid creating String objects with new String(). Stick to simple string primitives.

  • Remember: Strings are immutable. Every method returns a new string — they don't modify the original.

Strings power everything from form fields to error messages. The more we understand how to clean, format, and search through them, the smoother our Javascript code becomes.

And honestly? Once we master these tools, we stop fighting with strings and start making them work for us.

Stay tuned and keep your code clean! 🚀

0
Subscribe to my newsletter

Read articles from Sangy K directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sangy K
Sangy K

An Introvert Coder | Trying to be a Full-stack Developer | A Wannabe Content Creator