JavaScript Strings
-
Text Representation: Strings in JavaScript are used to represent textual data. They are enclosed within either single quotes (‘…’), double quotes (“…”), or backticks (“).
-
Examples:
JavaScriptconst greeting = "Hello, world!"; const name = 'John Doe'; const multilineString = `This is a multiline string`; -
String Methods: JavaScript provides a rich set of methods for manipulating strings:
length: Returns the number of characters in the string.toUpperCase(): Converts the string to uppercase.toLowerCase(): Converts the string to lowercase.indexOf(): Finds the index of the first occurrence of a substring.slice(): Extracts a portion of the string.concat(): Concatenates two or more strings.split(): Splits a string into an array of substrings.replace(): Replaces occurrences of a specified substring with another string.trim(): Removes whitespace from both ends of the string.
-
Template Literals: Backticks (“) allow for embedded expressions within strings:
JavaScriptconst name = "Alice"; const message = `Hello, ${name}!`; // Output: "Hello, Alice!"
Strings are fundamental in JavaScript, used for displaying text, handling user input, and building dynamic content within web pages.