Javascript string
Created By: chatGPT
JavaScript strings are used to represent text. A string can be defined using single quotes, double quotes, or backticks.
let singleQuoteString = 'Hello, World!';
let doubleQuoteString = "Hello, World!";
let templateLiteralString = `Hello, World!`;
String concatenation is the process of joining two or more strings together. You can use the
+
operator or template literals for this purpose.let firstName = 'John';
let lastName = 'Doe';
let fullName = firstName + ' ' + lastName;
// Using template literals
let fullNameTemplate = `${firstName} ${lastName}`;
You can access individual characters in a string using bracket notation. Strings are zero-indexed, meaning the first character is at index 0.
let greeting = 'Hello';
let firstCharacter = greeting[0];
let secondCharacter = greeting[1]; // 'e'
JavaScript provides many built-in methods for manipulating strings, such as
.length
, .toUpperCase()
, and .substring()
.let message = 'Hello, World!';
let messageLength = message.length; // 13
let upperCaseMessage = message.toUpperCase(); // 'HELLO, WORLD!'
let subMessage = message.substring(0, 5); // 'Hello'
You can also find and replace parts of a string using the
.replace()
method. To search for a substring, simply provide the current string and the substring to replace.let originalString = 'Hello, John!';
let newString = originalString.replace('John', 'Doe'); // 'Hello, Doe!'
Splitting a string into an array of substrings can be done with the
.split()
method. This is useful when you want to separate values by a specific delimiter.let csv = 'apple,banana,cherry';
let fruits = csv.split(','); // ['apple', 'banana', 'cherry']
Trimming whitespace from the beginning and end of a string can be accomplished using the
.trim()
method.let userInput = ' Hello, World! ';
let trimmedInput = userInput.trim(); // 'Hello, World!'