Working with Text: Strings and Regular Expressions
Slice it, search it, split it, and match it - become a text wizard in Node.
- measure a string and read single characters by their position,
- slice a piece out of a string and search inside it,
- change case, trim spaces, and split and join text,
- build strings neatly with template literals,
- replace text, and use a first regular expression to match and validate patterns.
1. What is a string?
A string is a piece of text: a word, a sentence, an emoji-free label, or even an empty ''. You write one by wrapping characters in single quotes, double quotes, or backticks:
const name = 'Ada';
const city = "Lovelace City";
const greeting = `Hello there`;
Analogy. Think of a string as a necklace of beads. Each bead is one character, and the beads are kept in a fixed order. You can count the beads, look at the third bead, or take a section of the necklace - but you cannot change one bead in place, because in JavaScript strings are immutable (read-only). Every "change" actually builds a brand-new string.
Strings live everywhere in the earlier topics of this course: the text you read with the fs module, the keys and values inside JSON, and the arguments you pull off process.argv in a CLI are all strings. Mastering strings makes all of those easier.