JavaScript String Methods tutorial for beginners

In the previous tutorial, you learned how to store data in objects. Most of that data is text: names, emails, cities, passwords and messages. To clean, search and change text, we use JavaScript String Methods. In this tutorial, you will learn 20 essential methods with practical code.

What is a String?

A string is text written inside quotes. You can use single quotes, double quotes or backticks.

let name = "Ali";
let city = 'Karachi';
let message = `Welcome to Tutorials Ocean`;

console.log(name, city, message);

Strings work like arrays of characters. Each character has an index starting from 0.

Index 0 1 2 3 4
Character H e l l o
let word = "Hello";

console.log(word[0]);    // H
console.log(word[4]);    // o
console.log(word.at(-1)); // o (last character)

Important: strings are immutable. This means string methods never change the original string. They always return a new string.

let text = "hello";
text[0] = "H";           // does nothing
console.log(text);       // hello (unchanged)

text = text.toUpperCase();   // we must save the new result
console.log(text);           // HELLO

1. length

Gives the number of characters (including spaces). It is a property, so no brackets are needed.

let text = "Hello World";

console.log(text.length);  // 11

2. toUpperCase() and toLowerCase()

let name = "Ali Khan";

console.log(name.toUpperCase());  // ALI KHAN
console.log(name.toLowerCase());  // ali khan
console.log(name);                // Ali Khan (original unchanged)

// Real use: case-insensitive comparison
let input = "KARACHI";
if (input.toLowerCase() === "karachi") {
  console.log("Match found");
}

3. trim(), trimStart() and trimEnd()

Remove extra spaces. Very useful for form inputs.

let input = "   ali@example.com   ";

console.log(input.trim());       // "ali@example.com"
console.log(input.trimStart());  // "ali@example.com   "
console.log(input.trimEnd());    // "   ali@example.com"

4. indexOf() and lastIndexOf()

Find the position of a word or letter. If not found, it returns -1.

let text = "I love JavaScript, JavaScript is fun";

console.log(text.indexOf("JavaScript"));      // 7
console.log(text.lastIndexOf("JavaScript"));  // 19
console.log(text.indexOf("Python"));          // -1

5. includes(), startsWith() and endsWith()

These return true or false.

let email = "ali@gmail.com";

console.log(email.includes("@"));          // true
console.log(email.includes("yahoo"));      // false
console.log(email.startsWith("ali"));      // true
console.log(email.endsWith(".com"));       // true
console.log(email.endsWith(".pk"));        // false

6. slice()

Takes a part of the string. Syntax: slice(start, end). The end index is not included.

let text = "JavaScript";

console.log(text.slice(0, 4));   // Java
console.log(text.slice(4));      // Script
console.log(text.slice(-6));     // Script (from the end)
console.log(text.slice(-6, -3)); // Scr

7. substring()

Similar to slice(), but it does not accept negative numbers.

let text = "JavaScript";

console.log(text.substring(0, 4));  // Java
console.log(text.substring(4, 10)); // Script

Tip: in modern code, most developers prefer slice().

8. replace() and replaceAll()

let text = "I like Java. Java is great.";

// replace: only the first match
console.log(text.replace("Java", "JavaScript"));
// I like JavaScript. Java is great.

// replaceAll: every match
console.log(text.replaceAll("Java", "JavaScript"));
// I like JavaScript. JavaScript is great.

// Real use: remove dashes from a phone number
let phone = "0300-123-4567";
console.log(phone.replaceAll("-", ""));  // 03001234567

9. split()

Converts a string into an array. You choose the separator.

let skills = "HTML,CSS,JavaScript,PHP";
console.log(skills.split(","));   // ["HTML", "CSS", "JavaScript", "PHP"]

let sentence = "Learn JavaScript step by step";
console.log(sentence.split(" ")); // ["Learn", "JavaScript", "step", "by", "step"]

let word = "Hello";
console.log(word.split(""));      // ["H", "e", "l", "l", "o"]

// Count words in a sentence
console.log(sentence.split(" ").length);  // 5

10. join() with split(): Reverse a String

You learned join() in the arrays tutorial. Together with split() it can reverse any text.

let text = "JavaScript";

let reversed = text.split("").reverse().join("");
console.log(reversed);  // tpircSavaJ

11. charAt() and charCodeAt()

let text = "Hello";

console.log(text.charAt(0));      // H
console.log(text.charAt(10));     // "" (empty string, no error)
console.log(text[10]);            // undefined
console.log(text.charCodeAt(0));  // 72 (ASCII code of H)

12. repeat()

console.log("Ha".repeat(3));    // HaHaHa
console.log("-".repeat(20));    // --------------------
console.log("* ".repeat(5));    // * * * * *

13. padStart() and padEnd()

Add extra characters to reach a fixed length. Useful for formatting numbers and masking data.

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

let card = "1234567812345678";
let lastFour = card.slice(-4);
console.log(lastFour.padStart(card.length, "*"));  // ************5678

console.log("Ali".padEnd(8, ".") + "Done");  // Ali.....Done

14. concat() and Template Literals

There are three ways to join strings.

let first = "Ali";
let last = "Khan";

// Way 1: + operator
console.log(first + " " + last);

// Way 2: concat()
console.log(first.concat(" ", last));

// Way 3: template literal (best, modern way)
console.log(`${first} ${last}`);

// Template literals make long text easy
let age = 22;
let city = "Karachi";
console.log(`My name is ${first} ${last}, I am ${age} years old from ${city}.`);

Template literals use backticks and ${ }. We will study them in more detail in the ES6 series.

15. search() and match() (Quick Preview)

These work with regular expressions. For now, just see a simple use.

let text = "My phone is 0300 and my code is 4567";

console.log(text.search("phone"));   // 3

// match with a simple pattern: find all digits groups
console.log(text.match(/\d+/g));     // ["0300", "4567"]

Method Chaining

You can use several JavaScript String Methods one after another. Each method works on the result of the previous one.

let input = "   ALI KHAN   ";

let clean = input.trim().toLowerCase();
console.log(clean);   // ali khan

let slug = "  Learn JavaScript Step By Step  "
  .trim()
  .toLowerCase()
  .replaceAll(" ", "-");

console.log(slug);    // learn-javascript-step-by-step

Loop Through a String

let word = "Karachi";

// for loop
for (let i = 0; i < word.length; i++) {
  console.log(i + ": " + word[i]);
}

// for...of
for (let letter of word) {
  console.log(letter);
}

Practical Example 1: Capitalize First Letter

function capitalize(text) {
  if (text.length === 0) {
    return text;
  }
  return text[0].toUpperCase() + text.slice(1).toLowerCase();
}

console.log(capitalize("javaSCRIPT"));  // Javascript
console.log(capitalize("ali"));         // Ali

Practical Example 2: Capitalize Every Word

function titleCase(sentence) {
  let words = sentence.toLowerCase().split(" ");
  let result = [];

  for (let word of words) {
    result.push(word[0].toUpperCase() + word.slice(1));
  }

  return result.join(" ");
}

console.log(titleCase("learn javascript step by step"));
// Learn Javascript Step By Step

Practical Example 3: Count Vowels

function countVowels(text) {
  let vowels = "aeiou";
  let count = 0;

  for (let letter of text.toLowerCase()) {
    if (vowels.includes(letter)) {
      count++;
    }
  }

  return count;
}

console.log(countVowels("JavaScript"));      // 3
console.log(countVowels("Tutorials Ocean")); // 7

Practical Example 4: Palindrome Checker

A palindrome reads the same forward and backward, like “madam”.

function isPalindrome(text) {
  let clean = text.toLowerCase().replaceAll(" ", "");
  let reversed = clean.split("").reverse().join("");
  return clean === reversed;
}

console.log(isPalindrome("madam"));            // true
console.log(isPalindrome("Never odd or even")); // true
console.log(isPalindrome("hello"));            // false

Practical Example 5: Simple Email Validator

function isValidEmail(email) {
  email = email.trim().toLowerCase();

  if (email.length < 6) {
    return false;
  }
  if (!email.includes("@")) {
    return false;
  }
  if (email.startsWith("@") || email.endsWith("@")) {
    return false;
  }
  if (!email.endsWith(".com") && !email.endsWith(".pk")) {
    return false;
  }
  return true;
}

console.log(isValidEmail("ali@gmail.com"));    // true
console.log(isValidEmail("  Sara@Mail.pk "));  // true
console.log(isValidEmail("alimail.com"));      // false
console.log(isValidEmail("@gmail.com"));       // false

Practical Example 6: Create a URL Slug

function makeSlug(title) {
  return title
    .trim()
    .toLowerCase()
    .replaceAll(" ", "-");
}

console.log(makeSlug("  JavaScript String Methods  "));
// javascript-string-methods

Practical Example 7: Mask a Phone Number

function maskPhone(phone) {
  let lastThree = phone.slice(-3);
  return phone.slice(0, 4) + "*".repeat(phone.length - 7) + lastThree;
}

console.log(maskPhone("03001234567"));  // 0300****567

Practical Example 8: Show Text on a Webpage

<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="showName()">Show</button>
<p id="result"></p>

<script>
  function showName() {
    let name = document.getElementById("nameInput").value;
    name = name.trim();

    if (name.length === 0) {
      document.getElementById("result").innerText = "Please enter your name";
      return;
    }

    let formatted = name[0].toUpperCase() + name.slice(1).toLowerCase();
    document.getElementById("result").innerText = "Hello, " + formatted + "!";
  }
</script>

Do not worry about document.getElementById for now. We will learn it in the DOM tutorials.

Quick Reference Table

Method What it does Example
length Number of characters “Hello”.length gives 5
toUpperCase() All capital letters “ali” gives “ALI”
toLowerCase() All small letters “ALI” gives “ali”
trim() Removes spaces from both ends ” hi ” gives “hi”
indexOf() Position of text, or -1 “Hello”.indexOf(“l”) gives 2
includes() true or false “Hello”.includes(“ell”) gives true
startsWith() Checks the beginning “Hello”.startsWith(“He”) gives true
endsWith() Checks the end “Hello”.endsWith(“lo”) gives true
slice() Takes a part “Hello”.slice(1, 3) gives “el”
replace() Replaces the first match “aa”.replace(“a”, “b”) gives “ba”
replaceAll() Replaces all matches “aa”.replaceAll(“a”, “b”) gives “bb”
split() String to array “a,b”.split(“,”) gives [“a”, “b”]
repeat() Repeats the text “Ha”.repeat(2) gives “HaHa”
padStart() Adds characters at the start “5”.padStart(3, “0”) gives “005”

Common Mistakes to Avoid

let name = "ali";

// Mistake 1: forgetting that strings are immutable
name.toUpperCase();
console.log(name);          // ali (not changed!)

name = name.toUpperCase();  // CORRECT: save the result
console.log(name);          // ALI

// Mistake 2: using length with brackets
// console.log(name.length());   WRONG: length is a property
console.log(name.length);        // CORRECT

// Mistake 3: replace changes only the first match
let text = "a-b-c";
console.log(text.replace("-", ""));     // ab-c (only the first)
console.log(text.replaceAll("-", ""));  // abc  (all)

// Mistake 4: case-sensitive search
console.log("Hello".includes("hello"));                // false
console.log("Hello".toLowerCase().includes("hello"));  // true

Quick Recap

  • Strings are immutable, so methods return a new string and you must save it
  • length, toUpperCase(), toLowerCase() and trim() are used daily
  • indexOf(), includes(), startsWith() and endsWith() search text
  • slice() takes a part, replace() and replaceAll() change text
  • split() turns a string into an array, and join() turns it back
  • repeat(), padStart() and padEnd() help with formatting
  • Template literals with backticks make joining text easy
  • You can chain methods: text.trim().toLowerCase()

Great job! You now know the most useful JavaScript String Methods. Every form, search box, username and message in a real website uses these methods.

Practice Exercises

  1. Print the length of your full name and your name in uppercase and lowercase.
  2. Take the text " Hello JavaScript " and print it without extra spaces.
  3. Check if the email "student@tutorialsocean.com.pk" contains “@” and ends with “.pk”.
  4. Use slice() to print the first 5 letters and the last 3 letters of “Programming”.
  5. Replace every space in “I love web development” with a dash.
  6. Split the text "red,green,blue,yellow" into an array and print how many colors are there.
  7. Reverse the word “Karachi” using split(), reverse() and join().
  8. Write a function that counts how many times the letter “a” appears in a sentence.
  9. Write a function that returns the first letter of every word in a sentence (example: “Tutorials Ocean” gives “TO”).
  10. Use padStart() to print numbers 1 to 10 in a 3-digit format (001, 002 … 010).

Assignment

Build a Username and Password Checker:

  1. Create a function cleanUsername(name) that trims spaces, converts to lowercase and replaces spaces inside with underscores. Example: " Ali Khan " gives "ali_khan".
  2. Create a function isValidUsername(name)
About Author

Arshad Sultan

Arshad Sultan is the Founder of Tutorials Ocean and a Technical Architect & Full-Stack Developer with 15+ years of experience in PHP, Laravel, CRM development, API integrations, and AI-powered automation. He also runs Rapid Code, a software and AI automation agency, and has trained hundreds of students across Karachi's IT institutes since 2010.

Leave a Reply

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