JS String Methods

Overview

String methods in JavaScript are built-in functions designed to manipulate and work with strings. Strings represent sequences of characters and are widely used for handling textual data.


Common String Methods

length Property

Returns the number of characters in a string.

Try yourself
        
            let message = "Hello, world!";
console.log(message.length);   // Outputs: 13
        
    

concat() Method

Combines two or more strings.

Try yourself
        
            let firstName = "John";
let lastName = "Doe";
let fullName = firstName.concat(" ", lastName);   // John Doe
console.log(fullName);   // John Doe
        
    

toUpperCase() and toLowerCase() Methods

Converts string case.

Try yourself
        
            let text = "Hello, World!";
console.log(text.toUpperCase());   // Outputs: HELLO, WORLD!
console.log(text.toLowerCase());   // Outputs: hello, world!
        
    

Accessing Characters

Access individual characters using square bracket notation.

Try yourself
        
            let str = "JavaScript";
console.log(str[0]);   // Outputs: J
console.log(str[4]);   // Outputs: S
        
    

substring() Method

Extracts a portion of a string.

substring(startIndex, endIndex)
Try yourself
        
            let str = "Hello, world!";
let extracted = str.substring(0, 5);   // Hello
        
    

substr() Method

The substr() method in JavaScript is used to extract a substring from a string. The substring is a portion of the string that starts at a specified index and ends at another specified index.

substr(startIndex, length)
Try yourself
        
            // Original string
let originalString = "Hello, world!";

// Using substr() to extract a substring
let extractedSubstring = originalString.substr(7, 5);

// Displaying the extracted substring
console.log(extractedSubstring);  // Output: "world"
        
    

Searching and Replacing

Methods like indexOf(), lastIndexOf(), includes(), and replace().

Try yourself
        
            let text = "Hello, world!";
console.log(text.indexOf("world"));   // Outputs: 7
console.log(text.includes("Hello"));  // Outputs: true
console.log(text.replace("world", "Universe"));  // Hello, Universe!

        
    

String Splitting and Joining

1. split() divides a string into an array of substrings.

2. join() concatenates array elements into a single string.

Try yourself
        
            let fruits = "apple,banana,orange";
let fruitArray = fruits.split(",");   // ["apple", "banana", "orange"]
let joinedFruits = fruitArray.join(" - ");   // apple - banana - orange
        
    

padStart() and padEnd() methods

The padStart() and padEnd() methods are two new methods available on JavaScript strings in the ES2020 (ECMAScript 2020) standard. They allow for formatting a string by adding padding characters at the start or the end.

Try yourself
        
            const str = "123";

// Pad the string with zeros to a length of 5.
let res1 = str.padStart(5); // "00123"
console.log(res1);

// Pad the string with dashes to a length of 8.
let res2 = str.padStart(8, "-", "."); // "--123.."
console.log(res2);

// Pad the string with spaces to a length of 3.
let res3 = str.padEnd(3); // "123"
console.log(res3);

// Pad the string with asterisks to a length of 5.
let res4 = str.padEnd(5, "*"); // "*123*"
console.log(res4);
        
    

Trimming Whitespace

trim()Removes whitespace from both sides of a string

trimStart(): Removes leading whitespace from a string.

trimEnd(): Removes trailing whitespace from a string.

Try yourself
        
            let userInput = "   Hello, user!   ";
let trimmedInput = userInput.trim();   // Hello, user!

let trimmedStart = text.trimStart();      // "Hello, user!   "
let trimmedEnd = text.trimEnd();          // "   Hello, user!"
        
    

charAt() method

The charAt() method is used to retrieve the character at a specified index within a string. The index is a zero-based value, meaning the first character has an index of 0, the second character has an index of 1, and so on.

Try yourself
        
            const myString = "Hello, world!";
const firstCharacter = myString.charAt(0); // Retrieves the first character "H"
const sixthCharacter = myString.charAt(6); // Retrieves the seventh character "w"

console.log(firstCharacter) // "H"
console.log(sixthCharacter) // "w"
        
    

charCodeAt() method

The charCodeAt() method returns the Unicode value (UTF-16 code unit) of the character at the specified index in a string. Unicode is a character encoding standard that assigns unique numeric values (code points) to different characters from various writing systems.

Try yourself
        
            const myString = "ABC";
const firstCharCode = myString.charCodeAt(0); // Retrieves the Unicode value for "A" (65)
const secondCharCode = myString.charCodeAt(1); // Retrieves the Unicode value for "B" (66)
const thirdCharCode = myString.charCodeAt(2); // Retrieves the Unicode value for "C" (67)

console.log(firstCharCode) // "A" (65)
console.log(secondCharCode) // "B" (66)
console.log(thirdCharCode) // "C" (67)
        
    

String Conversion

Convert non-string values to strings using toString() or string interpolation.

Try yourself
        
            let number = 42;
let strNumber = number.toString();   // "42"
let strInterpolation = `The number is ${number}`;  // "The number is 42"