Strings are a fundamental data type in JavaScript, used to represent textual data. In JavaScript, strings are sequences of characters enclosed in single quotes ('), double quotes ("), or backticks (`). Understanding how to manipulate strings is essential for web development, as strings are often used for displaying content, processing user input, and performing various text operations.
Declaring Strings
You can declare strings using different types of quotes:
let doubleQuoteString = "Hello, World!";
let templateString = `Hello, World!`;
Template strings (or template literals) enclosed in backticks allow for multi-line strings and string interpolation.
Embedding Strings in HTML
Strings are frequently used in HTML for displaying content dynamically. You can embed JavaScript strings in HTML using various methods:
Using innerHTML Property:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Strings</title>
<script>
function displayString() {
let message = "Hello, this is a dynamic string!";
document.getElementById("output").innerHTML = message;
}
</script>
</head>
<body onload="displayString()">
<div id="output"></div>
</body>
</html>
Using textContent Property:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Strings</title>
<script>
function displayString() {
let message = "Hello, this is a dynamic string!";
document.getElementById("output").textContent = message;
}
</script>
</head>
<body onload="displayString()">
<div id="output"></div>
</body>
</html>
String Methods
JavaScript provides numerous built-in methods for manipulating strings. Here are some commonly used string methods:
length:
console.log(str.length); // Outputs: 13
toUpperCase and toLowerCase:
console.log(str.toUpperCase()); // Outputs: HELLO, WORLD!
console.log(str.toLowerCase()); // Outputs: hello, world!
charAt:
console.log(str.charAt(0)); // Outputs: H
indexOf:
console.log(str.indexOf('World')); // Outputs: 7
substring and slice:
console.log(str.substring(0, 5)); // Outputs: Hello
console.log(str.slice(7, 12)); // Outputs: World
replace:
console.log(str.replace('World', 'JavaScript')); // Outputs: Hello, JavaScript!
split:
let words = str.split(' ');
console.log(words); // Outputs: ["Hello,", "World!"]
trim:
console.log(str.trim()); // Outputs: Hello, World!
String Interpolation
Template literals allow embedding expressions within strings using ${}:
let message = `Hello, ${name}!`;
console.log(message); // Outputs: Hello, John!
Example: Building a Dynamic Web Page
Let's build a simple web page that demonstrates various string manipulations:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Strings Example</title>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
margin: 20px;
}
#output {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
}
</style>
<script>
function manipulateStrings() {
let originalString = " Hello, JavaScript! Let's manipulate strings. ";
let trimmedString = originalString.trim();
let upperCaseString = trimmedString.toUpperCase();
let lowerCaseString = trimmedString.toLowerCase();
let substring = trimmedString.substring(7, 18);
let replacedString = trimmedString.replace("JavaScript", "HTML and CSS");
let splitString = trimmedString.split(" ");
let output = `
<p>Original String: "${originalString}"</p>
<p>Trimmed String: "${trimmedString}"</p>
<p>Upper Case: "${upperCaseString}"</p>
<p>Lower Case: "${lowerCaseString}"</p>
<p>Substring (7, 18): "${substring}"</p>
<p>Replaced "JavaScript" with "HTML and CSS": "${replacedString}"</p>
<p>Split String by space: [${splitString.join(', ')}]</p>
`;
document.getElementById("output").innerHTML = output;
}
</script>
</head>
<body onload="manipulateStrings()">
<div class="container">
<h1>JavaScript Strings Example</h1>
<div id="output"></div>
</div>
</body>
</html>
Explanation of the Example
HTML Structure:
The HTML document includes a head section for metadata, styles, and scripts.
The body contains a div with the class "container" for organizing content, and an output div where the results will be displayed.
Basic CSS styles are added to enhance the appearance, including margins, padding, and borders.
JavaScript Function (manipulateStrings):- originalString: The initial string with extra spaces.
- trimmedString: Removes leading and trailing spaces using trim().
- upperCaseString: Converts the string to upper case using toUpperCase().
- lowerCaseString: Converts the string to lower case using toLowerCase().
- substring: Extracts a part of the string using substring().
- replacedString: Replaces "JavaScript" with "HTML and CSS" using replace().
- splitString: Splits the string by spaces using split(" ").
The results are concatenated into an HTML string and displayed in the output div.
More Advanced String Methods
includes: Checks if a string contains a specified substring.
console.log(str.includes("JavaScript")); // Outputs: true
startsWith: Checks if a string starts with a specified substring.
console.log(str.startsWith("Hello")); // Outputs: true
endsWith: Checks if a string ends with a specified substring.
console.log(str.endsWith("JavaScript!")); // Outputs: true
String Concatenation
You can concatenate strings using the + operator or the concat method.
Using + Operator:
let name = "World";
let message = greeting + ", " + name + "!";
console.log(message); // Outputs: Hello, World!
Using concat Method:
let name = "World";
let message = greeting.concat(", ", name, "!");
console.log(message); // Outputs: Hello, World!
Practice Excercise Practice now