String in JS

String in JS

·

2 min read

In JavaScript, a string is a sequence of characters enclosed in single or double quotes. For example:

let name = "John Doe";
let message = 'Hello World!';

Strings have several built-in methods that can be used to manipulate and retrieve information from strings. Some examples include:

1. .length:

This property returns the length of a string.

let name = "John Doe";
console.log(name.length); // Output: 8

2. .concat():

This method concatenates (joins) two or more strings and returns a new string.

let firstName = "John";
let lastName = "Doe";
let fullName = firstName.concat(" ", lastName);
console.log(fullName); // Output: "John Doe"

3. .toUpperCase():

This method converts all the characters in a string to uppercase.

let message = 'Hello World!';
console.log(message.toUpperCase()); // Output: "HELLO WORLD!"

4. .toLowerCase():

This method converts all the characters in a string to lowercase.

let message = 'Hello World!';
console.log(message.toLowerCase()); // Output: "hello world!"

5. .indexOf():

This method returns the index of the first occurrence of a specified string value.

let message = 'Hello World!';
console.log(message.indexOf("World")); // Output: 6

6. .slice():

This method extracts a part of a string and returns a new string.

let message = 'Hello World!';
console.log(message.slice(7)); // Output: "World!"

7. .split():

This method splits a string into an array of substrings.

let message = 'Hello World!';
console.log(message.split(" ")); // Output: ["Hello", "World!"]

8. .replace():

This method replaces a specified value with another value in a string.

let message = 'Hello World!';
console.log(message.replace("World", "Friend")); // Output: "Hello Friend!"

9. .trim():

This method removes whitespace from both ends of a string.

let message = '   Hello World!   ';
console.log(message.trim()); // Output: "Hello World!"

These are just a few examples of the built-in methods available for strings in JavaScript. Knowing how to use these methods can make it much easier to manipulate and work with strings in your code.