Sitemap
Press enter or click to view image in full size

JavaScript String Methods — A Fun and Unique Exploration!

--

Strings are everywhere in JavaScript! Whether you’re displaying messages, handling user input, or playing around with text, mastering string methods can make your coding journey smoother. Let’s dive into some of the most useful string methods

1. charAt(index) — Finding the Hidden Character!

📌 Returns the character at a specified index.

let superhero = “Iron Man”;

console.log(superhero.charAt(1)); // r

console.log(superhero.charAt(4)); // M

2. indexOf(substring) — The Detective!

📌 Finds the first occurrence of a substring and returns its index, or -1 if not found.

let sentence = “JavaScript is awesome!”;

console.log(sentence.indexOf(“is”)); // 11

console.log(sentence.indexOf(“Python”)); // -1

3. lastIndexOf(substring) — The Reverse Detective!

📌 Finds the last occurrence of a substring and returns its index, or -1 if not found.
let phrase = “Find the last apple in the apple basket”;

console.log(phrase.lastIndexOf(“apple”)); // 27

4. includes(substring) — Secret Code Detector!

📌 Checks if a string contains a given substring (returns true or false).

let message = “Adventure awaits in JavaScript!”;

console.log(message.includes(“JavaScript”)); // true

console.log(message.includes(“Python”)); // false

5. slice(start, end) — The Text Slicer!

📌 Extracts a portion of a string.

Get Ishwari J’s stories in your inbox

Join Medium for free to get updates from this writer.

let sentence = “Programming is an art!”;

console.log(sentence.slice(0, 11)); // Programming

6. substring(start, end) — Another Way to Slice!

📌 Similar to slice(), but doesn’t accept negative indexes.

let phrase = “Hello, world!”;

console.log(phrase.substring(0, 5)); // Hello

7. split(separator) — Break It Apart!

📌 Splits a string into an array based on a separator.

let words = “sun,moon,stars”;

console.log(words.split(“,”)); // [“sun”, “moon”, “stars”]

8. concat() — The String Builder!

📌 Joins two or more strings.

let firstName = “Peter”;

let lastName = “Parker”;

console.log(firstName.concat(“ “, lastName)); // Peter Parker

9. trim() — The Cleaner!

📌 Removes whitespace from both ends of a string.

let messyString = “ Hello, world! “;

console.log(messyString.trim()); // “Hello, world!”

10. repeat(n) — Echo Mode!

📌 Repeats a string multiple times.

let echo = “Echo! “;

console.log(echo.repeat(3)); // “Echo! Echo! Echo! “

--

--

Ishwari J
Ishwari J

Written by Ishwari J

Class of The Hacking School-A25. Learning MERN Stack Development.