JavaScript String Fundamentals

A string in JavaScript is a sequence of characters used to represent text.

Advertisement

โœ… Ways to create strings

let str1 = "Hello";
let str2 = 'World';
let str3 = `Hello World`; // Template literal

String Methods

๐Ÿ”น 1. length

Description: Returns the number of characters in a string.

let str = "Hello";
console.log(str.length); // 5

๐Ÿ”น 2. toUpperCase()

Description: Converts all characters to uppercase.

"hello".toUpperCase(); // "HELLO"

๐Ÿ”น 3. toLowerCase()

Description: Converts all characters to lowercase.

"HELLO".toLowerCase(); // "hello"

๐Ÿ”น 4. trim()

Description: Removes whitespace from both ends.

"  hi  ".trim(); // "hi"

๐Ÿ”น 5. trimStart() / trimEnd()

Description: Removes whitespace from start or end only.

"  hi".trimStart(); // "hi"
"hi ".trimEnd(); // "hi"

๐Ÿ”น 6. includes(substring)

Description: Checks if string contains a substring โ†’ returns true/false.

"JavaScript".includes("Script"); // true

๐Ÿ”น 7. startsWith()

Description: Checks if string starts with given value.

"Hello".startsWith("He"); // true

๐Ÿ”น 8. endsWith()

Description: Checks if string ends with given value.

"Hello".endsWith("lo"); // true

๐Ÿ”น 9. indexOf()

Description: Returns first index of substring, or -1 if not found.

"Hello".indexOf("l"); // 2

๐Ÿ”น 10. lastIndexOf()

Description: Returns last occurrence index.

"Hello".lastIndexOf("l"); // 3

๐Ÿ”น 11. slice(start, end)

Description: Extracts part of string (supports negative index).

"JavaScript".slice(0, 4); // "Java"
"Hello".slice(-2); // "lo"

๐Ÿ”น 12. substring(start, end)

Description: Similar to slice() but does not accept negative index.

"JavaScript".substring(4, 10); // "Script"

๐Ÿ”น 13. substr(start, length) โš ๏ธ Deprecated

Description: Extracts substring using length (not recommended now).

"Hello".substr(1, 3); // "ell"

๐Ÿ”น 14. replace(search, value)

Description: Replaces first match.

"Hello World".replace("World", "JS"); // "Hello JS"

๐Ÿ”น 15. replaceAll()

Description: Replaces all occurrences.

"a-b-c".replaceAll("-", ","); // "a,b,c"

๐Ÿ”น 16. split(separator)

Description: Converts string into array.

"a,b,c".split(","); // ["a", "b", "c"]

๐Ÿ”น 17. concat()

Description: Joins two or more strings.

"Hello".concat(" ", "World"); // "Hello World"

๐Ÿ”น 18. charAt(index)

Description: Returns character at given index.

"Hello".charAt(1); // "e"

๐Ÿ”น 19. charCodeAt(index)

Description: Returns Unicode value of character.

"A".charCodeAt(0); // 65

๐Ÿ”น 20. repeat(n)

Description: Repeats string n times.

"Hi ".repeat(3); // "Hi Hi Hi "

๐Ÿ”น 21. padStart(length, char)

Description: Pads string from start.

"5".padStart(3, "0"); // "005"

๐Ÿ”น 22. padEnd(length, char)

Description: Pads string from end.

"5".padEnd(3, "0"); // "500"

๐Ÿ”น 23. match(regex)

Description: Returns matches based on regex.

"abc123".match(/\d+/); // ["123"]

๐Ÿ”น 24. matchAll(regex)

Description: Returns all matches (iterator).

[..."a1b2".matchAll(/\d/g)]; // ["1", "2"]

๐Ÿ”น 25. search(regex)

Description: Returns index of first match.

"hello123".search(/\d/); // 5

๐Ÿ”น 26. localeCompare()

Description: Compares two strings (useful for sorting).

"a".localeCompare("b"); // -1

๐Ÿ”น 27. normalize()

Description: Normalizes Unicode characters.

"รฉ".normalize(); 

๐Ÿ”น 28. valueOf()

Description: Returns primitive string value.

let str = new String("hello");
str.valueOf(); // "hello"

๐Ÿ”น 29. toString()

Description: Converts object to string.

let str = new String("hello");
str.toString(); // "hello"

๐Ÿ”น 30. Template Literals (`)

Description: Allows interpolation and multi-line strings.

let name = "John";
console.log(`Hello ${name}`);

โšก Quick Categorization

๐Ÿ” Search Methods

  • includes(), indexOf(), search()

โœ‚๏ธ Extract Methods

  • slice(), substring(), substr()

๐Ÿ”„ Modify Methods

  • replace(), replaceAll(), trim()

๐Ÿ”ง Utility Methods

  • split(), concat(), repeat()

๐Ÿ”ก Case Methods

  • toUpperCase(), toLowerCase()

๐Ÿ”ฅ 20 JavaScript String Programs (with Solutions)


โœ… 1. Reverse a string

let str = "hello";
let reversed = str.split("").reverse().join("");
console.log(reversed);

โœ… 2. Check palindrome

let str = "madam";
let result = str === str.split("").reverse().join("");
console.log(result);

โœ… 3. Count vowels

let str = "hello";
let count = str.match(/[aeiou]/gi)?.length || 0;
console.log(count);

โœ… 4. Count consonants

let str = "hello";
let count = str.match(/[^aeiou]/gi).length;
console.log(count);

โœ… 5. Remove spaces

let str = "h e l l o";
console.log(str.replaceAll(" ", ""));

โœ… 6. Convert first letter to uppercase

let str = "hello";
console.log(str.charAt(0).toUpperCase() + str.slice(1));

โœ… 7. Find longest word

let str = "I love JavaScript programming";
let words = str.split(" ");
let longest = words.reduce((a, b) => a.length > b.length ? a : b);
console.log(longest);

โœ… 8. Count words

let str = "Hello world JS";
console.log(str.split(" ").length);

โœ… 9. Check substring exists

let str = "JavaScript";
console.log(str.includes("Script"));

โœ… 10. Replace all vowels with *

let str = "hello";
console.log(str.replace(/[aeiou]/gi, "*"));

โœ… 11. Convert string to array

let str = "hello";
console.log(str.split(""));

โœ… 12. Remove duplicate characters

let str = "aabbcc";
let unique = [...new Set(str)].join("");
console.log(unique);

โœ… 13. Count character frequency

let str = "hello";
let obj = {};
for (let ch of str) {
obj[ch] = (obj[ch] || 0) + 1;
}
console.log(obj);

โœ… 14. Check anagram

let a = "listen";
let b = "silent";let result = a.split("").sort().join("") === b.split("").sort().join("");
console.log(result);

โœ… 15. Capitalize each word

let str = "hello world";
let result = str.split(" ").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
console.log(result);

โœ… 16. Extract numbers from string

let str = "abc123xyz";
console.log(str.match(/\d+/)[0]);

โœ… 17. Check if string contains only digits

let str = "12345";
console.log(/^\d+$/.test(str));

โœ… 18. Repeat string N times

let str = "hi";
console.log(str.repeat(3));

โœ… 19. Truncate string

let str = "JavaScript";
console.log(str.slice(0, 4));

โœ… 20. Convert string to title case

let str = "javascript is fun";
let result = str.split(" ")
.map(w => w[0].toUpperCase() + w.slice(1))
.join(" ");
console.log(result);

✎ Practise what you learned: 32 JavaScript string programs with solutions →

1 thought on “JavaScript String Fundamentals”

Leave a Comment