In JavaScript, a string is a primitive data type used to represent and manipulate a sequence of characters, such as text. Strings are immutable, meaning their content cannot be changed after they are created; any operation that seems to modify a string actually creates a new one.
Creating Strings
Strings can be created using three types of quotes:
- Single quotes:
'Hello world' - Double quotes:
"Hello world" - Template literals (backticks):
`Hello world`
Template literals, introduced in ES6, offer additional functionality like multiline strings and embedded expressions using the
${expression} syntax, which provides a clean way to concatenate variables and strings. const name = "Chris";
const greeting = `Hello, ${name}`; // "Hello, Chris"
Key Characteristics and Operations
- Immutability: You cannot change individual characters in a string directly. For example,
str[0] = 'H';will not work. You must create a new string with the desired modification. - Indexing: Characters can be accessed using zero-based indexing (e.g.,
str[0]) or the.charAt()method. The newer.at()method also allows for negative indices to access characters from the end of the string. - Length Property: The built-in
.lengthproperty returns the number of characters in a string (e.g.,str.length). - Concatenation: Strings can be joined using the
+operator or the.concat()method. - Escape Characters: The backslash (
\) is used to escape special characters, such as including quotes within a same-quoted string ('I\'m the Walrus') or creating new lines (\n).
Common String Methods
JavaScript provides a rich set of built-in methods for working with strings. These methods do not modify the original string; they return a new string.
Quotes inside Quotes:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>You can use quotes inside a string, as long as they don't match the quotes
surrounding the string.</p>
<p id="demo"></p>
<script>
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
document.getElementById("demo").innerHTML =
answer1 + "<br>" + answer2 + "<br>" + answer3;
</script>
</body>
</html>
Template Strings allow variables in strings.
Template strings provide an easy way to interpolate variables in strings.
let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
HTML Templates
Basic String Methods
Javascript strings are primitive and immutable: All string methods produce a new string without altering the original string.
No comments:
Post a Comment