Essential String Methods

Strings in JavaScript come with a rich set of built-in methods. Remember that strings are immutable, meaning these methods always return a new string and never modify the original.

JavaScript


const message = "   Hello, World! I am learning JS.   ";

// Getting the length
console.log(message.length); // 38

// Changing case
console.log(message.toUpperCase()); // "   HELLO, WORLD! I AM LEARNING JS.   "

// Trimming whitespace
console.log(message.trim()); // "Hello, World! I am learning JS."

// Checking for inclusion
console.log(message.includes("World")); // true
console.log(message.startsWith("   Hello")); // true

// Slicing: extracts a part of the string
// slice(startIndex, endIndex (optional))
console.log(message.trim().slice(0, 5)); // "Hello"

// Splitting a string into an array
const words = message.trim().split(" ");
console.log(words); // ["Hello,", "World!", "I", "am", "learning", "JS."]

Template Literals (ES6) Template literals, using backticks (`), are a modern way to create strings. They allow for embedded expressions and multi-line strings, which is much cleaner than traditional string concatenation.

JavaScript


const name = "Alex";
const score = 95;

// Old way
const reportOld = "User: " + name + "\nScore: " + score;

// New way with template literals
const reportNew = `User: ${name}
Score: ${score}`;

console.log(reportNew);

Introduction to Regular Expressions (RegExp)

A Regular Expression is a sequence of characters that forms a search pattern. It's like a mini-language for finding and manipulating text. They can look intimidating, but even a basic understanding is incredibly useful.

You can create a RegExp in two ways:

  1. Literal: const regex = /pattern/flags; (e.g., /hello/i where i is a flag for case-insensitivity)
  2. Constructor: const regex = new RegExp("pattern", "flags");

Using RegExp with String Methods

Two common methods for using RegExp are .test() and .match().

  • .test(): A RegExp method that checks for a match and returns true or false.
  • Code Snippet: Validating an Email Format
  • JavaScript

// This is a simplified email regex for demonstration
const emailRegex = /^\S+@\S+\.\S+$/;

console.log(emailRegex.test("test@example.com")); // true
console.log(emailRegex.test("test@example"));     // false
console.log(emailRegex.test("test.com"));         // false
  • .match(): A string method that retrieves the matches when matching a string against a regex.
  • Code Snippet: Finding All Numbers in a String
  • JavaScript

const text = "My phone number is 123-456-7890 and my zip code is 90210.";

// \d+ means "one or more digits"
// g is the "global" flag, to find all matches, not just the first one
const numberRegex = /\d+/g;

const allNumbers = text.match(numberRegex);
console.log(allNumbers); // ["123", "456", "7890", "90210"]