JavaScript Strings

Work with text data effectively in JS apps.

methodstemplate literalssearch/replace

Table of Contents

JavaScript Strings Tutorial (Beginner -> Practical)

Strings are used to store and manipulate text in JavaScript. They are one of the most frequently used data types when working with user input, messages, and data display.

1. Creating Strings

You can create strings using single quotes, double quotes, or backticks.

let str1 = "Hello";
let str2 = 'World';
let str3 = `JavaScript`;

All three are valid, but backticks have extra features.

2. Template Literals (Backticks)

Template literals allow you to embed variables and expressions.

let name = "John";
let message = `Hello ${name}`;

console.log(message);

This is cleaner than using + for concatenation.

3. String Length

let text = "JavaScript";

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

4. Accessing Characters

let text = "Hello";

console.log(text[0]); // H
console.log(text[1]); // e

5. Common String Methods

let text = "JavaScript";

// Convert case
console.log(text.toUpperCase());
console.log(text.toLowerCase());

// Find text
console.log(text.includes("Script")); // true
console.log(text.indexOf("Script"));  // 4

// Extract part
console.log(text.slice(0, 4)); // Java

// Replace
console.log(text.replace("Java", "Type"));

6. String Concatenation

let first = "Hello";
let second = "World";

let result = first + " " + second;
console.log(result);

// Better way
let result2 = `${first} ${second}`;

7. Trimming Spaces

let text = "   Hello   ";

console.log(text.trim()); // "Hello"

8. Splitting Strings

Convert string into array.

let text = "apple,banana,mango";

let arr = text.split(",");
console.log(arr);

9. Visual Understanding

Think of strings as indexed character sequences (0, 1, 2...). Most methods return a new string instead of changing the original.

10. Real-Life Example

let email = " user@example.com ";

email = email.trim();

if (email.includes("@")) {
    console.log("Valid Email");
} else {
    console.log("Invalid Email");
}

11. Important Tips

  • Strings are immutable (you cannot change characters directly).
  • Use methods like replace() to modify output safely.
  • Example: let text = "Hello"; text[0] = "Y"; will not change original string.

12. When to Use Strings

Strings are used for names, messages, user input, URLs, emails, and display content.

JavaScript String Important Functions (Quick Reference Table)

Common string methods for tutorials, revision, and interview prep.

FunctionSyntaxDescription
lengthstr.lengthReturns length of string
toUpperCase()str.toUpperCase()Converts to uppercase
toLowerCase()str.toLowerCase()Converts to lowercase
includes()str.includes("text")Checks substring exists
indexOf()str.indexOf("text")Returns first index or -1
lastIndexOf()str.lastIndexOf("text")Returns last index
slice()str.slice(start, end)Extracts part
substring()str.substring(start, end)Similar to slice (no negative index)
replace()str.replace("old","new")Replaces first occurrence
replaceAll()str.replaceAll("old","new")Replaces all occurrences
trim()str.trim()Removes spaces both sides
trimStart()str.trimStart()Removes start spaces
trimEnd()str.trimEnd()Removes end spaces
split()str.split(",")Converts string to array
charAt()str.charAt(index)Returns char at index
charCodeAt()str.charCodeAt(index)Returns ASCII/Unicode value
startsWith()str.startsWith("text")Checks beginning text
endsWith()str.endsWith("text")Checks ending text
concat()str1.concat(str2)Joins strings
repeat()str.repeat(n)Repeats string n times
let text = " JavaScript ";

console.log(text.trim());        // "JavaScript"
console.log(text.toUpperCase()); // " JAVASCRIPT "
console.log(text.includes("Script")); // true
console.log(text.slice(1, 5));   // "Java"

Related Topics

Data Types, Arrays, and Functions are commonly combined with string processing in real projects.

10 Strings Interview Q&A

1Are JS strings mutable?easy
Answer: No, strings are immutable.
2Difference between slice and substring?medium
Answer: slice supports negative indexes; substring does not.
3How to join array into string?easy
Answer: Use arr.join(",").
4How to check substring exists?easy
Answer: Use includes().
5Template literals advantage?easy
Answer: Supports interpolation and multiline strings.
6How to trim spaces?easy
Answer: Use trim().
7replace vs replaceAll?medium
Answer: replace updates first match unless regex with global flag; replaceAll updates all exact matches.
8How to split sentence into words?easy
Answer: Use split(" ").
9How to compare strings case-insensitively?medium
Answer: Convert both using same case and compare.
10What does string length count?easy
Answer: Number of UTF-16 code units.

10 Strings MCQs

1

Strings in JS are:

AMutable
BImmutable
CNumbers
DObjects only
Explanation: strings cannot be changed in place.
2

Uppercase conversion method:

Aupper()
BtoUpperCase()
Ccaps()
DsetUpper()
Explanation: built-in method is toUpperCase.
3

Template literals use:

Asingle quotes
Bdouble quotes
Cbackticks
Dbrackets
Explanation: interpolation works with backticks.
4

Method to check substring:

Acontains()
Bincludes()
Cfind()
Dexist()
Explanation: includes returns true/false.
5

split(",") returns:

Astring
Barray
Cboolean
Dnumber
Explanation: split breaks string into array pieces.
6

trim() removes:

Amiddle characters
Bleading/trailing spaces
Cnumbers
Dline breaks only
Explanation: trim strips whitespace at ends.
7

length is a:

Amethod
Bproperty
Cevent
Dclass
Explanation: length is property, not function.
8

Which gets first character?

Astr[0]
Bstr.first()
Cstr.char(0)
Dstr.get(0)
Explanation: bracket index or charAt can be used.
9

replaceAll affects:

Afirst match only
Ball matches
Cnone
Dnumbers only
Explanation: replaceAll updates all occurrences.
10

DOM text update usually uses:

AinnerText/textContent
BfontSize
Copacity
Ddisplay
Explanation: text nodes are managed via innerText/textContent.