🔡 JavaScript Strings & Template Literals
Estimated reading: 5 minutes 11 views

🧵 JavaScript — String Methods: Complete Guide with Examples & Explanations


🧲 Introduction — Why Mastering String Methods Matters

In JavaScript, strings are everywhere—from user inputs to server responses. Just knowing how to declare strings isn’t enough. 💡 To write efficient, clean, and readable code, developers must master JavaScript string methods.

By the end of this article, you will:

  • ✅ Understand 20+ string methods with real-world examples
  • ✅ Learn how to slice, search, transform, and format strings
  • ✅ Gain clarity on best practices and performance tips

🔑 What is a JavaScript String?

A string is a sequence of characters inside quotes:

let name = "JavaScript";

✅ This defines a variable name with the string value "JavaScript".
📘 Strings are immutable, so any operation returns a new string, not an edited one.


🧰 Common JavaScript String Methods

Let’s explore essential string methods with detailed code explanations:


🔤 length – Get String Length

let text = "JavaScript";
console.log(text.length); // 10

✅ Returns the total number of characters in text, which includes all letters from ‘J’ to ‘t’.


🎯 charAt(index) – Get Character by Index

let lang = "JavaScript";
console.log(lang.charAt(4)); // S

✅ Gets the character at index 4. Indexing starts from 0, so charAt(4) returns the 5th character: 'S'.


✂️ slice(start, end) – Extract a Section

let msg = "Hello, World!";
console.log(msg.slice(7, 12)); // World

slice(7, 12) returns characters starting at index 7 up to but not including 12.
📘 ‘W’ is at 7, and ‘d’ is at 11.


✂️ substring(start, end) – Alternative to slice

let text = "JavaScript";
console.log(text.substring(4, 10)); // Script

✅ Works like slice but doesn’t support negative indexes.
📘 It extracts from index 4 to 9.


📐 substr(start, length) – Extract by Length (Deprecated)

let text = "JavaScript";
console.log(text.substr(4, 3)); // Scr

✅ Extracts 3 characters starting from index 4. Returns 'Scr'.
⚠️ Avoid using this method—it is deprecated.


🔍 indexOf(substring) – First Match Index

let text = "Learn JavaScript";
console.log(text.indexOf("Script")); // 10

✅ Finds the first occurrence of 'Script'. Returns index 10.
📘 Returns -1 if not found.


🔍 lastIndexOf(substring) – Last Match Index

let text = "JavaScript is Java based";
console.log(text.lastIndexOf("Java")); // 17

✅ Searches from the end. 'Java' appears at 0 and again at 17. Returns last index.


🔎 includes(substring) – Check Existence

let text = "JavaScript";
console.log(text.includes("Script")); // true

✅ Checks if 'Script' exists inside the string. Returns true or false.


🎭 startsWith(prefix) / endsWith(suffix)

let lang = "JavaScript";
console.log(lang.startsWith("Java")); // true
console.log(lang.endsWith("Script")); // true

✅ Checks whether the string starts or ends with the given substring.


🔁 replace(search, replaceWith) – Replace Text

let msg = "I love JS!";
console.log(msg.replace("JS", "JavaScript")); // I love JavaScript!

✅ Replaces the first instance of 'JS' with 'JavaScript'.
📘 Use /pattern/g to replace all.


🧹 trim() / trimStart() / trimEnd()

let str = "   hello world   ";
console.log(str.trim());      // "hello world"
console.log(str.trimStart()); // "hello world   "
console.log(str.trimEnd());   // "   hello world"

✅ Removes whitespace from the string’s boundaries.


🔄 toUpperCase() / toLowerCase() – Change Case

let word = "Javascript";
console.log(word.toUpperCase()); // JAVASCRIPT
console.log(word.toLowerCase()); // javascript

✅ Converts all characters to upper or lower case.


🧱 concat() – Combine Strings

let a = "Hello";
let b = "World";
console.log(a.concat(" ", b)); // Hello World

✅ Joins multiple strings.
📘 Template literals or + are more modern.


🔡 split(delimiter) – Convert to Array

let csv = "apple,banana,grape";
console.log(csv.split(",")); // ['apple', 'banana', 'grape']

✅ Splits a string by a delimiter and returns an array.


🔁 repeat(count) – Repeat String

let text = "ha";
console.log(text.repeat(3)); // hahaha

✅ Repeats the string 3 times.


📏 padStart(length, char) / padEnd(length, char)

let num = "5";
console.log(num.padStart(3, "0")); // 005
console.log(num.padEnd(3, "0"));   // 500

✅ Pads the string from the start or end to meet the desired length.


🔧 match(regex) – Find with Regex

let data = "email@example.com";
console.log(data.match(/\w+@\w+\.\w+/)); // ['email@example.com']

✅ Returns the part of string matching the RegEx.


🔎 search(regex) – Find Index by Pattern

let text = "Visit JavaScript.com";
console.log(text.search(/script/i)); // 6

✅ Returns the index of the match. Case-insensitive with /i flag.


🧪 localeCompare() – Compare Strings

console.log("apple".localeCompare("banana")); // -1

✅ Returns -1, 0, or 1 based on alphabetical order.


📊 Comparison Table

MethodPurposeReturns
charAt()Character at indexSingle character
slice()Extract sectionNew string
indexOf()First occurrenceIndex or -1
includes()Check presencetrue or false
replace()Replace partNew string
trim()Remove whitespaceTrimmed string
toUpperCase()Convert to uppercaseNew string
split()Convert to arrayArray
padStart()Pad stringNew string
repeat()Repeat stringRepeated string

💡 Best Practices

  • 💬 Use includes() instead of indexOf() for clarity.
  • ⚠️ Avoid substr() as it’s deprecated.
  • 📘 Template literals (`) are better for dynamic strings.
  • 🚀 Use padStart() when formatting fixed-width outputs.

🧠 Summary

Mastering JavaScript string methods helps you manipulate and analyze text efficiently. Whether you’re formatting input, searching logs, or transforming API results — these tools are essential.


❓ FAQs

❓ What’s the difference between slice(), substring(), and substr()?

  • slice() allows negative indexes. substring() does not. substr() is deprecated.

❓ How to check if a string contains another?

  • Use .includes("text") for simple and readable logic.

❓ How to format numbers with leading zeros?

  • Use .padStart(): '5'.padStart(2, '0')'05'

❓ Best way to join strings?

  • Use template literals: `Hello ${name}` or +

❓ Can I modify a character in a string directly?

  • No. Strings are immutable. You must build a new string.

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript — String Methods

Or Copy Link

CONTENTS
Scroll to Top