JavaScript Strings: Concepts, Methods & Interactive Demo

Learn all about JavaScript strings – from basic concepts to essential methods with interactive examples.

Introduction to Strings

In JavaScript, a string is a sequence of characters used to represent text. Strings are enclosed in either single quotes ' ', double quotes " ", or backticks ` `. Importantly, strings are immutable – once created, their characters cannot be changed.

String Methods

Below is a table of many commonly used string methods along with short descriptions and example usage notes.

Method Description & Example
length Returns string length. E.g., "hello".length // 5
slice(start, end) Extracts substring. E.g., "hello".slice(1, 4) // "ell"
substring(start, end) Similar to slice but doesn't allow negative indexes. E.g., "hello".substring(1, 4) // "ell"
substr(start, length) Extracts part of string with specified length. E.g., "hello".substr(1, 3) // "ell"
toUpperCase() Converts to uppercase. E.g., "hello".toUpperCase() // "HELLO"
toLowerCase() Converts to lowercase. E.g., "HELLO".toLowerCase() // "hello"
concat() Concatenates strings. E.g., "Hello".concat(" ", "World") // "Hello World"
trim() Removes spaces from both ends. E.g., " hello ".trim() // "hello"
indexOf(substring) Returns first index of substring. E.g., "hello".indexOf("l") // 2
lastIndexOf(substring) Returns last index of substring. E.g., "hello".lastIndexOf("l") // 3
includes(substring) Checks if substring exists. E.g., "hello".includes("ll") // true
startsWith(substring) Checks if string starts with substring. E.g., "hello".startsWith("he") // true
endsWith(substring) Checks if string ends with substring. E.g., "hello".endsWith("lo") // true
replace(old, new) Replaces first occurrence of a substring. E.g., "hello".replace("l", "p") // "heplo"
replaceAll(old, new) Replaces all occurrences. E.g., "hello".replaceAll("l", "p") // "heppo"
split(separator) Splits string into an array. E.g., "a,b,c".split(",") // ["a","b","c"]
charAt(index) Returns character at index. E.g., "hello".charAt(1) // "e"
charCodeAt(index) Returns Unicode value at index. E.g., "A".charCodeAt(0) // 65

Q35. Print Each Character on a New Line


// Q35: Print each character on a new line
let prompt = require("prompt-sync")();
let str = prompt("Enter a string: ");
for (let i = 0; i < str.length; i++) {
  console.log(str[i]);
}
        

Note: In a browser, use prompt() and console.log() for demonstration.

Q36. Reverse the String


// Q36: Reverse a string
let prompt = require("prompt-sync")();
let str = prompt("Enter a string: ");
let reversed = "";
for (let i = str.length - 1; i >= 0; i--) {
  reversed += str[i];
}
console.log("Reversed string:", reversed);
        

In the browser, you can output the reversed string using alert() or DOM manipulation.

Interactive Demo: Try Out String Methods

Enter a string and choose a method to see its effect. Additional parameter inputs will appear as needed.