#atom
ID: CS-009
Date: [Insert Date]
Content:
In JavaScript, a string is a primitive data type used to represent textual data. Strings are immutable, meaning once created, they cannot be changed. However, JavaScript provides many methods for manipulating strings and creating new ones.
Ways to Create Strings in JavaScript:
-
Using Single Quotes:
const str1 = 'Hello, World!';
-
Using Double Quotes:
const str2 = "Hello, World!";
-
Using Backticks (Template Literals):
const str3 = `Hello, World!`;
-
Using the
String
Constructor:const str4 = String('Hello, World!');
-
Creating Multiline Strings:
- Using backticks (template literals):
const multilineStr = ` This is a multiline string. `;
- Using concatenation:
const multilineStr = 'This is a\n' + 'multiline\n' + 'string.';
- Using backticks (template literals):
-
Creating Strings from Variables (Interpolation):
const name = 'Alice'; const greeting = `Hello, ${name}!`; // "Hello, Alice!"
Common String Methods in JavaScript:
-
length
: Get the length of a string.const str = 'Hello'; console.log(str.length); // 5
-
toUpperCase()
andtoLowerCase()
: Convert case.const str = 'Hello'; console.log(str.toUpperCase()); // "HELLO" console.log(str.toLowerCase()); // "hello"
-
substring()
andslice()
: Extract substrings.const str = 'Hello, World!'; console.log(str.substring(0, 5)); // "Hello" console.log(str.slice(-6)); // "World!"
-
indexOf()
andincludes()
: Search for substrings.const str = 'Hello, World!'; console.log(str.indexOf('World')); // 7 console.log(str.includes('Hello')); // true
-
replace()
: Replace parts of a string.const str = 'Hello, World!'; console.log(str.replace('World', 'Alice')); // "Hello, Alice!"
-
trim()
: Remove whitespace from the beginning and end.const str = ' Hello, World! '; console.log(str.trim()); // "Hello, World!"
Connections:
Connections:
Sources: