- JavaScript Introduction
- JavaScript Where To
- JavaScript Output
- JavaScript Statements
- JavaScript Syntax
- JavaScript Comments
- JavaScript Variables
- JavaScript Let
- JavaScript Const
- JavaScript Operators
- JavaScript Assignment
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Events
- JavaScript Strings
- JavaScript String Methods
- JavaScript Numbers
- JavaScript Number Methods
- JavaScript Arrays
- JavaScript Array Const
- JavaScript Array Methods
- JavaScript Sorting Arrays
- JavaScript Array Iteration
- JavaScript Date Objects
- JavaScript Date Formats
- JavaScript Get Date Methods
- JavaScript Set Date Methods
- JavaScript Math Object
- JavaScript Random
- JavaScript Booleans
- JavaScript Comparison And Logical Operators
- JavaScript If Else And Else If
- JavaScript Switch Statement
- JavaScript For Loop
- JavaScript Break And Continue
- JavaScript Type Conversion
- JavaScript Bitwise Operations
- JavaScript Regular Expressions
- JavaScript Errors
- JavaScript Scope
- JavaScript Hoisting
- JavaScript Use Strict
- The JavaScript This Keyword
- JavaScript Arrow Function
- JavaScript Classes
- JavaScript JSON
- JavaScript Debugging
- JavaScript Style Guide
- JavaScript Common Mistakes
- JavaScript Performance
- JavaScript Reserved Words
- JavaScript Versions
- JavaScript History
- JavaScript Forms
- JavaScript Validation API
- JavaScript Objects
- JavaScript Object Properties
- JavaScript Function Definitions
- JavaScript Function Parameters
- JavaScript Function Invocation
- JavaScript Closures
- JavaScript Classes
- Java Script Async
- JavaScript HTML DOM
- The Browser Object Model
- JS Ajax
- JavaScript JSON
- JavaScript Web APIs
- JS Vs JQuery
JavaScript Strings
JavaScript Strings
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
Escape Character
Escape characters in JavaScript are used to represent special characters within strings that would otherwise be difficult or impossible to include directly. These characters allow developers to include quotes, backslashes, newlines, and other special characters within strings.
Because strings must be written within quotes, JavaScript will misunderstand this string:
The string will be chopped to "We are the so-called ".
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\
) escape character turns special characters into string characters:
Code | Result | Description |
---|---|---|
\' | ' | Single quote |
\" | " | Double quote |
\\ | \ | Backslash |
The sequence \"
inserts a double quote in a string:
Example
The sequence \'
inserts a single quote in a string:
Example
The sequence \\
inserts a backslash in a string:
Example
Six other escape sequences are valid in JavaScript:
Code | Result |
---|---|
\b | Backspace |
\f | Form Feed |
\n | New Line |
\r | Carriage Return |
\t | Horizontal Tabulator |
\v | Vertical Tabulator |
The 6 escape characters above were originally designed to control typewriters, teletypes, and fax machines. They do not make any sense in HTML.
Explanation of the Complex Example
HTML Structure:
The HTML document includes a head section with metadata, styles, and a script.
The body contains a h1 heading and a div with the class "container" that includes a pre element for displaying preformatted text.
CSS Styling:
Basic styles are applied to the body and the container to improve the appearance.
The pre element has a background color, padding, and a border to make the preformatted text stand out.
JavaScript Function (displayData):
- Various strings are defined using escape characters: name, address, quote, path, and heart.
- A template literal (formattedData) is used to format the data, including newlines and other escape sequences.
- The textContent property of the pre element is set to the formatted data, ensuring that the special characters are correctly displayed.
Additional Advanced Usage of Escape Characters
Escaping Characters in Regular Expressions
When working with regular expressions, certain characters need to be escaped to be treated as literals:
let str = "hello.";
console.log(regex.test(str)); // Outputs: true
In this example, the dot (.) is escaped to match an actual dot character in the string.
Escaping HTML Entities
When dynamically inserting HTML content, it is sometimes necessary to escape HTML entities to prevent code injection and ensure correct rendering:
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
let userInput = "<script>alert('XSS');</script>";
let safeInput = escapeHtml(userInput);
document.getElementById("output").innerHTML = safeInput;
This function replaces special HTML characters with their corresponding HTML entities, ensuring that user input is safely displayed.
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP