JavaScript Strings and String Methods: Complete Guide with Examples

Most of what a tester checks is text: page titles, error messages, URLs, table cells, API fields and log lines. JavaScript strings come with dozens of built-in methods to search, cut, clean, change and compare text. In this lesson you will learn how strings work, the methods you will use every day, the difference between similar methods such as slice and substring, and how to clean real UI text before an assertion.

Advertisement

📖 What You’ll Learn: creating strings with quotes and escapes, length and indexing, at(), immutability, searching with includes, startsWith, endsWith and indexOf, extracting with slice and substring, changing case, trim, padStart and padEnd, repeat, replace and replaceAll, split and join, comparing strings with localeCompare, Unicode and emoji length, and cleaning UI text for tests.


🔤 Creating Strings

Definition: a string is a sequence of characters used to represent text. You write string literals with double quotes, single quotes or back-ticks:

📄 create.js

const double = "QA Engineer";
const single = 'Playwright';
const backtick = `Score: ${40 + 2}`;   // template literal, next lesson

console.log(double, "|", single, "|", backtick);
console.log(typeof double, String(123), typeof String(123));

⌨️ Terminal

node create.js

🖥️ Output

QA Engineer | Playwright | Score: 42
string 123 string

Double and single quotes behave the same. Pick one style for your project (Prettier uses double quotes by default). Use the other kind when the text contains a quote, or escape it with a backslash:

📄 escapes.js

console.log("It's ready");
console.log('She said "pass"');
console.log("She said \"pass\"");
console.log("Line 1\nLine 2");      // \n = new line
console.log("Col1\tCol2");          // \t = tab
console.log("C:\\tests\\login.spec.js");   // \\ = one backslash

⌨️ Terminal

node escapes.js

🖥️ Output

It's ready
She said "pass"
She said "pass"
Line 1
Line 2
Col1	Col2
C:\tests\login.spec.js
EscapeMeaning
\nNew line
\tTab
\\Backslash
\" / \'Quote inside a string with the same quotes
\u{1F600}A Unicode character by code point

📏 Length, Indexes and at()

Each character has a position (an index) starting at 0. length is the number of characters.

📄 index.js

const word = "Selenium";

console.log(word.length);
console.log(word[0], word[3], word[word.length - 1]);
console.log(word[20]);            // out of range: undefined
console.log(word.at(0), word.at(-1), word.at(-2));   // at() accepts negative indexes

⌨️ Terminal

node index.js

🖥️ Output

8
S e m
undefined
S m u

💡 Tip: str.at(-1) (ES2022) is the clearest way to read the last character. With bracket notation you need str[str.length - 1].


🔒 Strings Are Immutable

Definition: immutable means a string cannot be changed after it is created. Every string method returns a new string and leaves the original untouched.

📄 immutable.js

let status = "passed";

status.toUpperCase();          // result is thrown away
console.log(status);

status[0] = "P";               // silently ignored
console.log(status);

status = status.toUpperCase(); // store the new string
console.log(status);

⌨️ Terminal

node immutable.js

🖥️ Output

passed
passed
PASSED

⚠️ Watch out: A very common bug is calling a method and not using its result: name.trim(); on its own line does nothing. Write name = name.trim(); or use the result directly.


Advertisement

🔍 Searching: includes, startsWith, endsWith, indexOf

📄 search.js

const url = "https://qa.example.com/checkout?step=2";

console.log(url.includes("checkout"));        // contains?
console.log(url.startsWith("https://"));      // begins with?
console.log(url.endsWith("step=2"));          // ends with?
console.log(url.indexOf("/"), url.lastIndexOf("/"));
console.log(url.indexOf("cart"));             // not found: -1
console.log(url.includes("Checkout"));        // case-sensitive!
console.log(url.toLowerCase().includes("Checkout".toLowerCase()));

⌨️ Terminal

node search.js

🖥️ Output

true
true
true
6 22
-1
false
true
MethodReturns
includes(text)true/false
startsWith(text) / endsWith(text)true/false
indexOf(text) / lastIndexOf(text)Position of the first / last match, or -1
search(regex)Position of the first regex match, or -1

All of these are case-sensitive. Lower-case both sides for a case-insensitive check.


✂️ Extracting: slice and substring

slice(start, end) returns the characters from start up to, but not including, end. Leave out end to go to the end of the string. Negative numbers count from the end.

📄 slice.js

const id = "ORD-2026-000451";

console.log(id.slice(0, 3));     // "ORD"
console.log(id.slice(4, 8));     // "2026"
console.log(id.slice(9));        // from index 9 to the end
console.log(id.slice(-6));       // last 6 characters
console.log(id.slice(-6, -3));

console.log(id.substring(4, 8)); // like slice for positive numbers
console.log(id.substring(8, 4)); // swaps the arguments if start > end
console.log(id.slice(8, 4));     // slice returns ""
console.log(id.substring(-6));   // negative numbers become 0

⌨️ Terminal

node slice.js

🖥️ Output

ORD
2026
000451
000451
000
2026
2026

ORD-2026-000451

💡 Tip: Prefer slice. It supports negative indexes and behaves the same as Array.prototype.slice. The old substr method is deprecated; do not use it in new code.

Combine indexOf and slice to cut text at a marker:

📄 cut.js

const email = "asha.rao@sqatools.in";
const at = email.indexOf("@");
console.log(email.slice(0, at), "|", email.slice(at + 1));

⌨️ Terminal

node cut.js

🖥️ Output

asha.rao | sqatools.in

🧹 Changing Case, Trimming, Padding and Repeating

📄 clean.js

const raw = "   Order CONFIRMED   ";

console.log(JSON.stringify(raw.trim()));
console.log(JSON.stringify(raw.trimStart()), JSON.stringify(raw.trimEnd()));
console.log(raw.trim().toLowerCase(), "|", raw.trim().toUpperCase());

const invoice = "42";
console.log(invoice.padStart(6, "0"));     // "000042"
console.log("Total".padEnd(10, ".") + "₹499");

console.log("=".repeat(20));
console.log("ab".repeat(3));

⌨️ Terminal

node clean.js

🖥️ Output

"Order CONFIRMED"
"Order CONFIRMED   " "   Order CONFIRMED"
order confirmed | ORDER CONFIRMED
000042
Total.....₹499
====================
ababab
  • trim() removes spaces, tabs and line breaks from both ends; text copied from web pages often has them.
  • padStart/padEnd fill a string to a target length, useful for IDs and aligned report columns.
  • toUpperCase/toLowerCase help with case-insensitive comparisons.

🔁 replace and replaceAll

replace(search, replacement) replaces the first match only when search is a string. replaceAll (ES2021) replaces every match.

📄 replace.js

const price = "₹1,29,999";

console.log(price.replace(",", ""));        // only the first comma
console.log(price.replaceAll(",", ""));     // every comma
console.log(price.replace(/[₹,]/g, ""));    // regex with g flag: all matches

const template = "Hello {name}, your order {id} has shipped";
const message = template.replace("{name}", "Asha").replace("{id}", "#451");
console.log(message);

⌨️ Terminal

node replace.js

🖥️ Output

₹129,999
₹129999
129999
Hello Asha, your order #451 has shipped

Regular expressions (lesson 27) make replace far more powerful, for example to remove every non-digit character.


Advertisement

✂️ split and join

split(separator) breaks a string into an array. The array method join(separator) does the reverse.

📄 split-join.js

const csvRow = "asha,tester,Pune,active";
const fields = csvRow.split(",");
console.log(fields, fields.length);

const [name, role] = fields;
console.log(name, role);

console.log("a b  c".split(" "));          // two spaces give an empty item
console.log("a b  c".split(/\s+/));       // regex: any run of whitespace
console.log("QA".split(""));              // into characters
console.log("x,y,z".split(",", 2));        // limit the number of parts

const tags = ["smoke", "login", "p1"];
console.log(tags.join(", "), "|", tags.join("-"));

const slug = "  Learn JavaScript Strings  ".trim().toLowerCase().split(" ").join("-");
console.log(slug);

⌨️ Terminal

node split-join.js

🖥️ Output

[ 'asha', 'tester', 'Pune', 'active' ] 4
asha tester
[ 'a', 'b', '', 'c' ]
[ 'a', 'b', 'c' ]
[ 'Q', 'A' ]
[ 'x', 'y' ]
smoke, login, p1 | smoke-login-p1
learn-javascript-strings

⚖️ Comparing Strings

=== compares exactly, including case and spaces. < and > compare by character codes, so uppercase letters sort before lowercase ones. localeCompare compares the way people expect for a language:

📄 compare.js

console.log("apple" === "Apple");
console.log("Zebra" < "apple");                       // code order: true
console.log("apple".localeCompare("Zebra"));          // negative: apple first

const names = ["ravi", "Asha", "émile", "Bala"];
console.log([...names].sort());                        // code order
console.log([...names].sort((a, b) => a.localeCompare(b)));   // human order

console.log("résumé".localeCompare("RESUME", "en", { sensitivity: "base" }) === 0);

⌨️ Terminal

node compare.js

🖥️ Output

false
true
-1
[ 'Asha', 'Bala', 'ravi', 'émile' ]
[ 'Asha', 'Bala', 'émile', 'ravi' ]
true

💡 Tip: When a test checks that a table column is sorted, build the expected order with localeCompare (or Intl.Collator) in the same locale as the application.


😀 Unicode, Emoji and length

JavaScript strings are made of UTF-16 code units. Most characters use one unit, but many emoji and some rare characters use two, so length can be larger than the number of visible characters:

📄 unicode.js

const text = "QA 👍";
console.log(text.length);                // 5, not 4
console.log([...text].length);           // spread splits by code point: 4
console.log(text.slice(0, 4));           // may cut an emoji in half
console.log([...text].slice(0, 4).join(""));
console.log("👍".codePointAt(0).toString(16));

⌨️ Terminal

node unicode.js

🖥️ Output

5
4
QA �
QA 👍
1f44d

⚠️ Watch out: If a form limits input to “20 characters”, find out whether the application counts code units or visible characters, and test with emoji and accented letters. These are classic boundary-test cases.


🧪 Tester Scenario: Clean and Check UI Text

Text from a web page often contains extra spaces, line breaks and different case. This helper normalises text before comparing, and a second helper extracts values from a summary line:

📄 ui-text.js

function normalise(text) {
  return text.replace(/\s+/g, " ").trim().toLowerCase();
}

function expectTextEquals(actual, expected) {
  const ok = normalise(actual) === normalise(expected);
  console.log(`${ok ? "PASS" : "FAIL"}: "${normalise(actual)}" vs "${normalise(expected)}"`);
  return ok;
}

expectTextEquals("  Welcome back,\n   ASHA!  ", "Welcome back, Asha!");
expectTextEquals("Order #451 shipped", "Order #452 shipped");

const summary = "Showing 1–25 of 1,204 results for \"laptop\"";
const total = Number(summary.slice(summary.indexOf("of ") + 3, summary.indexOf(" results")).replaceAll(",", ""));
const term = summary.slice(summary.indexOf("\"") + 1, summary.lastIndexOf("\""));
console.log({ total, term });

⌨️ Terminal

node ui-text.js

🖥️ Output

PASS: "welcome back, asha!" vs "welcome back, asha!"
FAIL: "order #451 shipped" vs "order #452 shipped"
{ total: 1204, term: 'laptop' }

Playwright’s toHaveText and toContainText already normalise whitespace, but you need helpers like these when you read text with textContent() and process it yourself.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Print the first character, the last character and the length of "automation".

Show answer

📄 practice1.js

const word = "automation";
console.log(word[0], word.at(-1), word.length);

🖥️ Output

a n 10

Q2. Write capitalize(str) that makes the first letter uppercase and the rest lowercase: "pLAYWRIGHT" → "Playwright".

Show answer

📄 practice2.js

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
console.log(capitalize("pLAYWRIGHT"), capitalize("a"), JSON.stringify(capitalize("")));

🖥️ Output

Playwright A ""

Q3. Count how many times the letter "s" appears in "Tests pass successfully" (case-insensitive).

Show answer

📄 practice3.js

const text = "Tests pass successfully";
const count = text.toLowerCase().split("s").length - 1;
console.log(count);

🖥️ Output

7

Splitting on "s" creates one more piece than there are separators.

Q4. Mask a card number so only the last 4 digits show: "4111111111111111" → "************1111".

Show answer

📄 practice4.js

const card = "4111111111111111";
const masked = card.slice(-4).padStart(card.length, "*");
console.log(masked);

🖥️ Output

************1111

Q5. Convert " Login Page Title Test " into a file-name slug "login-page-title-test.spec.js".

Show answer

📄 practice5.js

const name = "  Login Page Title Test  ";
const file = name.trim().toLowerCase().split(/\s+/).join("-") + ".spec.js";
console.log(file);

🖥️ Output

login-page-title-test.spec.js

Q6. Check whether "Was it a car or a cat I saw" is a palindrome, ignoring spaces and case.

Show answer

📄 practice6.js

const text = "Was it a car or a cat I saw";
const clean = text.toLowerCase().replaceAll(" ", "");
const isPalindrome = clean === [...clean].reverse().join("");
console.log(clean, isPalindrome);

🖥️ Output

wasitacaroracatisaw true

🧠 MCQ Quiz: Strings and String Methods

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What is "JavaScript".length?
  2. What does "tester".at(-1) return?
  3. After let s = "abc"; s.toUpperCase(); what is s?
  4. What does "2026-11-23".slice(5, 7) return?
  5. What does "a,b,c".split(",") return?
  6. What does "1,000,000".replace(",", "") return?
  7. Which method checks whether a string begins with “https”?
  8. What does "QA".indexOf("x") return?
  9. What does "7".padStart(3, "0") return?
  10. Why can "👍".length be 2?

💼 Interview Questions and Answers

Q1. What is the difference between slice, substring and substr?

slice(start, end) extracts from start up to (not including) end and supports negative indexes. substring(start, end) is similar but treats negative values as 0 and swaps the arguments if start is larger than end. substr(start, length) takes a length instead of an end index and is deprecated. In modern code use slice.

Q2. Why are strings immutable, and what does that mean for your code?

Immutable means a string value never changes; methods like trim, replace and toUpperCase return new strings. That makes strings safe to share and compare by value, but you must store or use the returned value. Building a long string in a loop creates many intermediate strings; collecting parts in an array and calling join once is often clearer.

Q3. How do you replace all occurrences of a substring?

Use str.replaceAll("old", "new") (ES2021), or str.replace(/old/g, "new") with a global regex, or the older str.split("old").join("new"). Plain replace with a string pattern replaces only the first occurrence.

📄 replace-all.js

const s = "a-b-c";
console.log(s.replaceAll("-", "+"), s.replace(/-/g, "+"), s.split("-").join("+"));

⌨️ Terminal

node replace-all.js

🖥️ Output

a+b+c a+b+c a+b+c

Q4. How would you reverse a string, and what is the catch?

[...str].reverse().join("") spreads the string into code points, reverses the array and joins it. The older str.split("").reverse().join("") breaks emoji and other characters made of two UTF-16 units. Characters built from several code points (for example family emoji or some accented letters) need Intl.Segmenter to be reversed correctly.

Q5. How do you compare UI text robustly in a test?

Normalise both sides first: collapse whitespace (replace(/\s+/g, " ")), trim, and lower-case if case does not matter. Compare with === after normalising, or use matchers that already normalise (toHaveText). Avoid asserting on text that changes (dates, counters) without extracting and checking the dynamic part separately.


Advertisement

❓ Frequently Asked Questions

🤔 How do I check if a string contains a word in JavaScript?

Use str.includes("word"). For a case-insensitive check, lower-case both: str.toLowerCase().includes("word"). For whole-word matches use a regular expression with \b.

🤔 How do I convert a string to an array?

Use str.split(separator) to split on a separator, or [...str] / Array.from(str) to get individual characters.

🤔 What is the difference between single and double quotes?

None in behaviour. Choose one style for consistency and use the other (or escapes) when the text contains a quote. Back-ticks create template literals.

🤔 How do I remove spaces from a string?

Use trim() for the ends, replaceAll(" ", "") for every space, or replace(/\s+/g, "") for all whitespace including tabs and line breaks.


🏁 Summary

  • Strings are immutable sequences of characters; every method returns a new string.
  • Use length, indexes and at() to read characters; includes, startsWith, indexOf to search.
  • Use slice to extract, trim/padStart/toLowerCase to clean, replaceAll to replace.
  • split turns text into arrays and join turns arrays into text.
  • Normalise whitespace and case before comparing UI text, and remember emoji can count as two characters.

Next, continue with Lesson 26: Template Literals. For extra practice, solve the JavaScript string practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in