String Methods in JavaScript
What Is a String?
A String is a data type for storing text. JavaScript provides many built-in methods for manipulating strings.
let name = "John Smith";
let studentId = "2024100123";
console.log(typeof name); // "string"
console.log(name.length); // 13
The length Property
let name = "John Smith";
console.log(name.length); // 13
// Check whether a string is empty
let empty = "";
console.log(empty.length === 0); // true
// Validate that the StudentID must be 10 digits
function validationPanjangStudentID(studentId) {
return studentId.length === 10;
}
console.log(validationPanjangStudentID("2024100123")); // true
console.log(validationPanjangStudentID("2024100")); // false
charAt() — Get the Character at an Index
let name = "John Smith";
console.log(name.charAt(0)); // "B"
console.log(name.charAt(4)); // " " (space)
// Same as bracket notation
console.log(name[0]); // "B"
console.log(name[1]); // "u"
indexOf() — Find the Position of a Substring
let name = "John Smith";
console.log(name.indexOf("John")); // 0
console.log(name.indexOf("Smith")); // 5
console.log(name.indexOf("Eric")); // -1 (not found)
// Case sensitive
console.log(name.indexOf("Mike")); // -1
// Search from a specific position
let text = "John and Mike and Anna";
console.log(text.indexOf("and")); // 5
console.log(text.indexOf("and", 6)); // 14
includes() — Check for the Presence of a Substring
let name = "John Smith";
console.log(name.includes("John")); // true
console.log(name.includes("Mike")); // false (case sensitive)
console.log(name.includes("Eric")); // false
// Usage in an academic portal
function checkMajor(student) {
if (student.includes("Computer Science")) {
return "Major: Computer Science";
} else if (student.includes("Information Systems")) {
return "Major: Information Systems";
}
return "Major: Unknown";
}
slice() — Extracting a Portion of a String
let name = "John Smith";
// Slice from index 0 to 4
console.log(name.slice(0, 4)); // "John"
// Slice from index 5 to the end
console.log(name.slice(5)); // "Smith"
// Slice from the end
console.log(name.slice(-7)); // "Smith"
// Extract the year from the StudentID
let studentId = "2024100123";
let entryYear = "20" + studentId.slice(0, 2);
console.log(entryYear); // "2024"
substring() — Similar to slice
let text = "Welcome to Campus";
console.log(text.substring(8, 15)); // "Datang"
console.log(text.substring(8)); // "Datang to Campus"
// Difference from slice: substring does not accept negative indices
console.log(text.substring(-5)); // "Welcome to Campus"
console.log(text.slice(-5)); // "ampus"
replace() and replaceAll()
// replace() — replace the FIRST occurrence
let name = "John Smith John";
console.log(name.replace("John", "Mike")); // "Mike Smith John"
// replaceAll() — replace ALL occurrences (ES2021)
console.log(name.replaceAll("John", "Mike")); // "Mike Smith Mike"
// Case-insensitive replacement with a regex
let text = "Welcome to Campus";
console.log(text.replace(/campus/gi, "State University"));
// Replacement in an academic portal
function formatStudentID(studentId) {
return studentId.replace(/(\d{2})(\d{2})(\d{6})/, "$1/$2/$3");
}
console.log(formatStudentID("2024100123")); // "20/24/100123"
split() — Splitting a String into an Array
let name = "John Smith";
let words = name.split(" ");
console.log(words); // ["John", "Smith"]
let date = "15-05-2002";
let parts = date.split("-");
console.log(parts); // ["15", "05", "2002"]
// Split into characters
let letter = "John".split("");
console.log(letter); // ["B", "u", "d", "i"]
// Limit the split
let sentence = "Welcome di university";
console.log(sentence.split(" ", 2)); // ["Welcome", "to"]
// Reverse an array after splitting
function balikText(text) {
return text.split("").reverse().join("");
}
console.log(balikText("John")); // "iduB"
join() — Joining an Array into a String
// join() is called on an array, not a string
let arr = ["Programming", "Web"];
console.log(arr.join(" ")); // "Web Programming"
let arr2 = ["IF", "101"];
console.log(arr2.join("")); // "IF101"
// Format a student list
let nameArr = ["John", "Mike", "Anna"];
console.log(nameArr.join(", ")); // "John, Mike, Anna"
console.log(nameArr.join(" | ")); // "John | Mike | Anna"
trim(), trimStart(), trimEnd()
let text = " John Smith ";
console.log(text.trim()); // "John Smith"
console.log(text.trimStart()); // "John Smith "
console.log(text.trimEnd()); // " John Smith"
// Important for input validation
function validateInput(input) {
const cleaned = input.trim();
if (cleaned.length === 0) {
return { valid: false, message: "Input cannot be empty!" };
}
return { valid: true, value: cleaned };
}
console.log(validateInput(" ")); // { valid: false, message: "..." }
console.log(validateInput(" John ")); // { valid: true, value: "John" }
toUpperCase() and toLowerCase()
let name = "John Smith";
console.log(name.toUpperCase()); // "JOHN SMITH"
console.log(name.toLowerCase()); // "john smith"
// Case-insensitive comparison
function equals(first, second) {
return first.toLowerCase() === second.toLowerCase();
}
console.log(equals("John", "john")); // true
console.log(equals("John", "Mike")); // false
repeat()
let line = "-".repeat(30);
console.log(line); // "------------------------------"
// Creating a header
let title = "ACADEMIC";
let padding = " ".repeat(5);
console.log(`${padding}${title}${padding}`);
// " ACADEMIC "
startsWith() and endsWith()
let fileName = "IF101_PemrogramanWeb_Senin.pdf";
console.log(fileName.startsWith("IF")); // true
console.log(fileName.endsWith(".pdf")); // true
console.log(fileName.startsWith("IF101")); // true
// Validate the StudentID: it must start with the enrollment year
function validationEntryYear(studentId, year) {
return studentId.startsWith(year.toString());
}
console.log(validationEntryYear("2024100123", 2024)); // true
padStart() and padEnd()
// padStart — add characters at the beginning
let num = "42";
console.log(num.padStart(5, "0")); // "00042"
// padEnd — add characters at the end
let name = "John";
console.log(name.padEnd(15, ".")); // "John..........."
// Format the StudentID with leading zeros
function formatStudentID(num) {
return num.toString().padStart(4, "0");
}
console.log(formatStudentID(123)); // "0123"
console.log(formatStudentID(1)); // "0001"
// Neat table
const students = [
{ name: "John Smith", studentId: "2024100123", gpa: 3.75 },
{ name: "Mike Brown", studentId: "2024100124", gpa: 3.50 },
{ name: "Anna Green", studentId: "2024100125", gpa: 3.90 }
];
console.log("StudentID".padEnd(15) + "Name".padEnd(20) + "GPA");
console.log("-".repeat(40));
students.forEach(m => {
console.log(
m.studentId.padEnd(15) +
m.name.padEnd(20) +
m.gpa.toFixed(2)
);
});
match() — Finding a Pattern with a Regex
let email = "john.smith.ui.edu";
// Match an email
const emailRegex = /^[\w.-]+@[\w.-]+\.\w+$/;
console.log(email.match(emailRegex)); // match array or null
// Extract numbers from a string
let text = "Student in semester 3 takes 18 credits";
let numbers = text.match(/\d+/g);
console.log(numbers); // ["3", "18"]
// Check the StudentID format
function validationFormatStudentID(studentId) {
const regex = /^\d{10}$/;
return studentId.match(regex) !== null;
}
console.log(validationFormatStudentID("2024100123")); // true
console.log(validationFormatStudentID("2024100")); // false
search() — Finding the Position of a Pattern
let text = "Welcome di Portal Academic";
console.log(text.search(/Portal/)); // 20
console.log(text.search(/portal/i)); // 20 (case insensitive)
console.log(text.search(/xyz/)); // -1 (not found)
// Difference from indexOf: search supports regex
console.log(text.indexOf(/Portal/)); // Error!
console.log(text.search(/Portal/)); // 20
Case Study: Validating StudentID Format and Name Format
// === STUDENT DATA VALIDATION SYSTEM ===
// StudentID validation
function validationStudentID(studentId) {
const errors = [];
// Check the type
if (typeof studentId !== "string") {
errors.push("StudentID must be a string!");
return { valid: false, errors };
}
// Check the length
if (studentId.length !== 10) {
errors.push(`StudentID must be 10 characters (current: ${studentId.length})`);
}
// Check that it contains only digits
if (!/^\d{10}$/.test(studentId)) {
errors.push("StudentID can only contain digits!");
}
// Check the enrollment year
const entryYear = parseInt("20" + studentId.substring(0, 2));
const currentYear = new Date().getFullYear();
if (entryYear > currentYear) {
errors.push("Enrollment year is invalid!");
}
// Check the semester from the StudentID
const majorCode = studentId.substring(2, 4);
const validMajor = ["10", "11", "12", "20", "21"];
if (!validMajor.includes(majorCode)) {
errors.push("Major code is invalid!");
}
return {
valid: errors.length === 0,
errors,
parsed: {
entryYear: "20" + studentId.substring(0, 2),
majorCode: majorCode,
sequenceNumber: studentId.substring(4)
}
};
}
// Format a name
function formatName(name) {
if (typeof name !== "string" || name.trim().length === 0) {
return { valid: false, message: "Name cannot be empty!" };
}
// Clean up excess spaces
let cleaned = name.trim().replace(/\s+/g, " ");
// Check for at least 2 words
const words = cleaned.split(" ");
if (words.length < 2) {
return { valid: false, message: "Name must be at least 2 words!" };
}
// Check for letters and spaces only
if (!/^[a-zA-Z\s]+$/.test(cleaned)) {
return { valid: false, message: "Name can only contain letters!" };
}
// Format: Title Case
const formatted = words
.map(k => k.charAt(0).toUpperCase() + k.slice(1).toLowerCase())
.join(" ");
return {
valid: true,
original: name,
formatted: formatted,
initials: words.map(k => k.charAt(0).toUpperCase()).join(". ") + "."
};
}
// Format a university email
function formatEmail(name, studentId) {
const cleanName = name.toLowerCase()
.replace(/\s+/g, ".")
.replace(/[^a-z.]/g, "");
const cleanStudentID = studentId.replace(/\D/g, "").slice(-8);
return `${cleanName}.${cleanStudentID}@student.ui.edu`;
}
// === USAGE ===
// Test StudentID validation
console.log("=== STUDENT ID VALIDATION ===");
const studentIdTests = ["2024100123", "2024100", "abcdefghij", "2099100123"];
studentIdTests.forEach(studentId => {
const result = validationStudentID(studentId);
console.log(`\nStudentID: ${studentId}`);
if (result.valid) {
console.log(` ✅ Valid — Year: ${result.parsed.entryYear}`);
} else {
console.log(` ❌ Invalid — ${result.errors.join(", ")}`);
}
});
// Test name formatting
console.log("\n\n=== NAME FORMAT ===");
const nameTests = ["john smith", "MIKE WILLIAMS", " anna dana ", "eric"];
nameTests.forEach(name => {
const result = formatName(name);
console.log(`\nInput: "${name}"`);
if (result.valid) {
console.log(` ✅ Formatted: ${result.formatted}`);
console.log(` Initials: ${result.initials}`);
} else {
console.log(` ❌ ${result.message}`);
}
});
// Test email formatting
console.log("\n\n=== FORMAT EMAIL ===");
console.log(formatEmail("John Smith", "2024100123"));
// "[email protected]"
Summary
| Method | Function | Return |
|---|---|---|
length |
String length | number |
charAt(i) |
Character at index | string |
indexOf(s) |
Position of first substring | number/-1 |
includes(s) |
Check for substring presence | boolean |
slice(a, b) |
Extract part of a string | string |
substring(a, b) |
Extract a portion (no negatives) | string |
replace(a, b) |
Replace first occurrence | string |
replaceAll(a, b) |
Replace all occurrences | string |
split(d) |
Split into an array | array |
trim() |
Remove leading/trailing spaces | string |
toUpperCase() |
All uppercase | string |
toLowerCase() |
All lowercase | string |
repeat(n) |
Repeat the string n times | string |
startsWith(s) |
Check the prefix | boolean |
endsWith(s) |
Check the suffix | boolean |
padStart(l, c) |
Pad at the beginning | string |
padEnd(l, c) |
Pad at the end | string |
match(r) |
Find a regex pattern | array/null |
search(r) |
Find the position of a pattern | number/-1 |
String methods are very important for input validation, data formatting, and text manipulation in an academic portal.