HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript String Methods

String methods help you work with and manipulate text. It is important to remember that all string methods return a new string. They do not modify the original string, as strings in JavaScript are immutable.


Extracting String Parts

There are three common methods for extracting a part of a string:

1. slice(start, end)

Extracts a part of a string and returns the extracted part in a new string.

let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13); // Result: "Banana"

2. substring(start, end)

Similar to slice(), but it cannot accept negative indexes.

let str = "Hello World";
console.log(str.substring(0, 5)); // Result: "Hello"

Changing Case

You can easily convert a string to uppercase or lowercase using these methods:

let text = "Hello World!";
let upper = text.toUpperCase(); // "HELLO WORLD!"
let lower = text.toLowerCase(); // "hello world!"

Replacing Content

The replace() method replaces a specified value with another value in a string.

let message = "Please visit Microsoft!";
let newMsg = message.replace("Microsoft", "RedoHub"); 

console.log(newMsg); // "Please visit RedoHub!"
Note: By default, replace() only replaces the first match. Use replaceAll() to replace all occurrences.

Trimming and Cleaning

The trim() method removes whitespace from both sides of a string.

let text = "      Hello World!      ";
let clean = text.trim(); 

console.log(clean); // "Hello World!"

Converting to an Array

A string can be converted into an array with the split() method.

let csv = "Red,Blue,Green";
let colors = csv.split(","); // ["Red", "Blue", "Green"]

Extracting Characters

You can get specific characters from a string using charAt() or property access [].

let text = "HELLO";
console.log(text.charAt(0)); // "H"
console.log(text[1]);        // "E"

Key Points to Remember

  • String methods do not change the original string
  • Use slice() or substring() to get parts of a string
  • replace() helps swap text, but usually only for the first match
  • trim() is essential for cleaning user input spaces
  • split() is the way to turn a string into a usable array