Previous Next

JavaScript Strings

A string in JavaScript is a primitive data type that represents a sequence of characters. It is enclosed by single quotes (' '), double quotes (" "), or backticks (' ').

Example:

let name1 = "Peter";
let name2 = 'Perker';
let greeting = `Hello ${name}!`;

String Methods

JavaScript has several built-in methods for manipulating strings.

length

The length method returns the length of a string.

Example:

let str = "Hello JavaScript";
console.log(str.length);

Output:

16

concat

The concat() method method is used to concatenate two or more strings.

Example:

let str1 = "Hello";
let str2 = " JavaScript";
console.log(str1.concat(str2));

Output:

Hello JavaScript

indexOf

The indexOf() method is used to find the index of a specific character in a string.

Example:

let str = "Hello JavaScript";
console.log(str.indexOf("J"));

Output:

6

replace

The replace() method replaces a string with another string.

Example:

let str = "Hello JavaScript";
console.log(str.replace("Hello", "I Love"));

Output:

I Love JavaScript

toUpperCase and toLowerCase

The toUpperCase() and toLowerCase() methods are used to convert a string to uppercase or lowercase letters.

Example:

let str = "Hello JavaScript";
console.log(str.toUpperCase());
console.log(str.toLowerCase());

Output:

HELLO JAVASCRIPT
hello javascript
Previous Next