JavaScript Strings:
In JavaScript, a string is a sequence of characters that is used to represent text. Strings are a fundamental data type in the language, and JavaScript provides various methods and properties to work with them.
Here are some key points about JavaScript strings:
1. Creating Strings:
Strings can be created using single quotes (`'`) or double quotes (`"`). Both forms are equivalent, and you can choose the one that fits your coding style.
javascript
let singleQuoted = 'This is a string.';
let doubleQuoted = "This is also a string.";
JavaScript Strings |
2. String Concatenation:
Strings can be concatenated using the `+` operator.
javascript
let firstName = 'John';
let lastName = 'Doe';
let fullName = firstName + ' ' + lastName; // Result: 'John Doe'
3. String Length:
The length of a string can be obtained using the `length` property.
javascript
let message = 'Hello, world!';
let messageLength = message.length; // Result: 13
4. Accessing Characters:
Individual characters in a string can be accessed using bracket notation with a zero-based index.
javascript
let word = 'JavaScript';
let firstLetter = word[0]; // Result: 'J'
5. String Methods:
JavaScript provides a variety of string methods for performing operations on strings. Some common methods include:
`toUpperCase()`: Converts a string to uppercase.
`toLowerCase()`: Converts a string to lowercase.
`indexOf()`: Returns the index of the first occurrence of a specified substring.
`substring()`: Extracts a portion of the string between two specified indices.
`split()`: Splits a string into an array of substrings based on a specified delimiter.
`replace()`: Replaces a specified substring or pattern with another string.
javascript
let text = 'Hello, world!';
let upperCaseText = text.toUpperCase(); // Result: 'HELLO, WORLD!'
let index = text.indexOf('world'); // Result: 7
let replacedText = text.replace('world', 'JavaScript'); // Result: 'Hello, JavaScript!'
6. Template Literals:
Template literals, introduced in ECMAScript 6 (ES6), allow the embedding of expressions within string literals.
javascript
let name = 'Alice';
let greeting = `Hello, ${name}!`; // Result: 'Hello, Alice!'
JavaScript provides a rich set of features for working with strings, making it versatile for text manipulation in web development.