Last Updated on May 28, 2024 by
JavaScript String Methods
#### Introduction to JavaScript String Methods
In this blog post, we will delve into the world of JavaScript string methods. JavaScript provides a variety of built-in methods that allow developers to modify and manipulate string values. We will explore these methods in detail, covering their functionality and usage. Additionally, we will provide examples of syntax that can be used in CodePen to solidify your understanding of these string methods. Let’s dive into the fascinating world of JavaScript string manipulation and learn how to leverage these powerful tools to enhance your web development skills.
JavaScript provides a variety of methods for working with strings. Here are some key string methods in JavaScript:
(1). charAt() Method:
This method returns the character at a specified index in a string. It takes a single parameter, the index of the character to be returned. JavaScript counts positions from zero. If the index is out of range, an empty string is returned.
Example:
const str = “Hello”;
console.log(str.charAt(0)); // Output: “H”
(2). slice() Method:
The slice() method is used to extract a section of a string and returns it as a new string, without modifying the original string. It takes two parameters: the start position and the end position. If the end position is omitted, the method will slice out the rest of the string.
Example:
const str = “Hello World”;
console.log(str.slice(6, 11)); // Output: “World”
(3). toUpperCase() Method:
This method returns the string converted to uppercase.
Example:
const str = “hello world”;
console.log(str.toUpperCase()); // Output: “HELLO WORLD”
(4). toLowerCase() Method:
This method returns the string converted to lowercase.
Example:
const str = “HELLO WORLD”;
console.log(str.toLowerCase()); // Output: “hello world”
(5). length Property:
The length property returns the length of a string.
Example:
let text = “Hello, World!”;
let length = text.length; // Returns 13
(6). trim():
Removes whitespace from both ends of a string.
Example:
const str = ” Hello World “;
console.log(str.trim()); // Output: “Hello World”
(7). concat(string1, string2, …):
Joins two or more strings.
Example:
const str1 = “Hello”;
const str2 = “World”;
console.log(str1.concat(” “, str2)); // Output: “Hello World”
NOTE:
https://youtu.be/p_Ro4u915oY