Strings are one of the most common JavaScript data types. They represent text and come with many built-in methods.
const text = "Hello";console.log(text.length); // 5const text = "Hello World";
console.log(text.toUpperCase()); // "HELLO WORLD"console.log(text.toLowerCase()); // "hello world"Common methods include:
slicesubstringsubstr (legacy, generally avoid in new code)const text = "JavaScript";
console.log(text.slice(0, 4)); // "Java"console.log(text.substring(4, 10)); // "Script"const text = "I love JavaScript";
console.log(text.includes("Java")); // trueconsole.log(text.indexOf("Java")); // 7console.log(text.startsWith("I")); // trueconsole.log(text.endsWith("Script")); // trueconst text = "Hello Tom";
console.log(text.replace("Tom", "Alice")); // "Hello Alice"const text = " hello world ";
console.log(text.trim()); // "hello world"console.log(text.trimStart()); // "hello world "console.log(text.trimEnd()); // " hello world"const sentence = "I love JavaScript and Node.js";const words = sentence.split(" ");
console.log(words);// ["I", "love", "JavaScript", "and", "Node.js"]"ha".repeat(3); // "hahaha"Template literals make string interpolation and multi-line strings easier.
const name = "Tom";console.log(`Hello, ${name}`);The most common string operations in daily development are:
If you are comfortable with these, you can handle most text manipulation tasks in JavaScript.