Strings
In JavaScript, a string
is a data type used to represent text rather than numbers or other types of values. Strings are enclosed in either single quotes (' '
), double quotes (" "
), or backticks (` `
).
length
property of a string tells you how many characters are in it.Strings in JavaScript can be declared in three ways:
let message = 'Hello, world!';
let message = "Hello, world!";
let message = `Hello, world!`;
You can find the number of characters in a string using the length
property.
let length = string.length;
Example:
let message = "Hello, world!";
console.log(message.length); // Output: 13
String concatenation is the process of combining two or more strings together.
let combinedString = string1 + string2;
Example:
let greeting = "Hello";
let name = "Alice";
let message = greeting + ", " + name + "!";
console.log(message); // Output: Hello, Alice!
JavaScript provides several built-in methods that allow you to manipulate strings. Here are some commonly used ones:
toUpperCase()
This method converts the entire string to uppercase.
let upperCaseString = string.toUpperCase();
Example:
let message = "hello";
console.log(message.toUpperCase()); // Output: HELLO
toLowerCase()
This method converts the entire string to lowercase.
let lowerCaseString = string.toLowerCase();
Example:
let message = "HELLO";
console.log(message.toLowerCase()); // Output: hello
slice()
This method extracts a part of a string, based on the given start and end index.
let slicedString = string.slice(startIndex, endIndex);
Example:
let message = "Hello, world!";
console.log(message.slice(0, 5)); // Output: Hello
replace()
This method replaces a substring with another string.
let newString = string.replace(oldSubstring, newSubstring);
Example:
let message = "Hello, world!";
console.log(message.replace("world", "Alice")); // Output: Hello, Alice!
In JavaScript, escape sequences are used to insert special characters in strings, such as newline characters, tab characters, etc.
\n
β Newline\t
β Tab\\
β Backslash\'
β Single quote\"
β Double quotelet message = "Hello,\nworld!"; console.log(message); // Output: Hello, // world!
Try working with strings and applying methods. Hereβs a simple task:
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!