In JavaScript, a string is a sequence of characters enclosed in single or double quotes. Strings can be manipulated using various string methods available in JavaScript.
Declaring a string in JavaScript
To declare a string variable in JavaScript, use the following syntax
let stringVariable = 'Hello, World!';
This declares a string variable named stringVariable
and assigns the value 'Hello, World!'
to it.
String methods
There are many built-in string methods in JavaScript. Here are some commonly used ones:
length
: returns the length of the string
let str = 'Hello, World!';
console.log(str.length); // Outputs: 13
toUpperCase()
: converts the string to uppercase
let str = 'Hello, World!';
console.log(str.toUpperCase()); // Outputs: HELLO, WORLD!
toLowerCase()
: converts the string to lowercase
let str = 'Hello, World!';
console.log(str.toLowerCase()); // Outputs: hello, world!
4.indexOf(): returns the index of the first occurrence of a specified substring
let str = 'Hello, World!';
console.log(str.indexOf('o')); // Outputs: 4
substring()
: returns a substring of the string
let str = 'Hello, World!';
console.log(str.substring(0, 5)); // Outputs: Hello
replace()
: replaces a specified substring with another string
let str = 'Hello, World!';
console.log(str.replace('World', 'Universe')); // Outputs: Hello, Universe!
Concatenating strings
You can concatenate strings in JavaScript using the +
operator or the concat()
method. Here’s an example using the +
operator:
let firstName = 'John';
let lastName = 'Doe';
console.log(firstName + ' ' + lastName); // Outputs: John Doe
String interpolation
String interpolation allows you to embed expressions inside a string literal. In JavaScript, you can use template literals (enclosed in backticks) for string interpolation. Here’s an example:
let firstName = 'John';
let lastName = 'Doe';
console.log(`My name is ${firstName} ${lastName}.`); // Outputs: My name is John Doe.
Strings are a fundamental data type in JavaScript, and manipulating strings is a common task in web development. Understanding string methods and concatenation techniques is important for working with strings effectively in JavaScript.