Labs ICT
Pro Login

Strings

2 min read | JavaScript Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

String Basics

Strings represent text. You can use single quotes, double quotes, or backticks.

const single = 'Hello';
const double = "World";
const template = `Hello, ${double}!`;

console.log(template); // Hello, World!

Accessing Characters and Length

Use bracket notation or charAt to access characters. The length property gives the string size.

const text = "JavaScript";
console.log(text[0]);       // J
console.log(text.charAt(4)); // S
console.log(text.length);   // 10

Changing Case

toUpperCase and toLowerCase transform the entire string.

const word = "Hello World";
console.log(word.toUpperCase()); // HELLO WORLD
console.log(word.toLowerCase()); // hello world

Searching Within Strings

Use indexOf, includes, startsWith, and endsWith to search.

const sentence = "The quick brown fox";
console.log(sentence.includes("fox"));    // true
console.log(sentence.startsWith("The"));  // true
console.log(sentence.endsWith("fox"));    // true
console.log(sentence.indexOf("brown"));   // 10

Extracting Substrings

slice, substring, and substr extract parts of a string. slice is the most flexible.

const str = "JavaScript";
console.log(str.slice(0, 4));   // Java
console.log(str.slice(4));      // Script
console.log(str.slice(-6));     // Script (negative index)

Replacing Content

replace replaces the first match. replaceAll replaces all matches.

const phrase = "I like cats. Cats are cute.";
console.log(phrase.replace("cats", "dogs"));       // I like dogs. Cats are cute.
console.log(phrase.replaceAll("cats", "dogs"));    // I like dogs. Cats are cute.
console.log(phrase.replaceAll(/cats/gi, "dogs")); // I like dogs. Dogs are cute.

Splitting and Joining

split breaks a string into an array. join does the reverse.

const csv = "apple,banana,cherry";
const fruits = csv.split(",");
console.log(fruits); // ["apple", "banana", "cherry"]

const list = fruits.join(" | ");
console.log(list);   // apple | banana | cherry

Trimming and Padding

trim removes whitespace. padStart and padEnd add padding.

const messy = "  spaced out  ";
console.log(messy.trim()); // "spaced out"

const id = "42";
console.log(id.padStart(5, "0")); // "00042"
console.log(id.padEnd(5, "X"));   // "42XXX"