Introduction: JavaScript provides a wide range of built-in methods that can be applied to strings. These methods allow you to manipulate and transform strings in various ways. In this documentation, we will explore some commonly used string methods in JavaScript, along with code examples and explanations.
Table of Contents:
length
- Finding the Length of a StringtoUpperCase()
andtoLowerCase()
- Converting CasecharAt()
andcharCodeAt()
- Accessing Charactersconcat()
- Concatenating Stringsslice()
- Extracting a SubstringindexOf()
andlastIndexOf()
- Searching for Substringsreplace()
- Replacing Substringssplit()
- Splitting a String into an Arraytrim()
- Removing WhitespacestartsWith()
andendsWith()
- Checking Start and Endsubstring()
andsubstr()
- Extracting Substrings
1. length
- Finding the Length of a String:
The length
property returns the number of characters in a string.
Code Example:
javascriptconst str = "Hello, World!";
console.log(str.length); // Output: 13
Explanation:
In the above example, the length
property is used to determine the length of the string str
, which contains 13 characters.
2. toUpperCase()
and toLowerCase()
- Converting Case:
The toUpperCase()
method converts all characters in a string to uppercase, while toLowerCase()
converts them to lowercase.
Code Example:
javascriptconst str = "Hello, World!";
console.log(str.toUpperCase()); // Output: HELLO, WORLD!
console.log(str.toLowerCase()); // Output: hello, world!
Explanation:
In the above example, toUpperCase()
is used to convert the string str
to uppercase, and toLowerCase()
is used to convert it to lowercase.
3. charAt()
and charCodeAt()
- Accessing Characters:
The charAt()
method returns the character at a specified index in a string, while charCodeAt()
returns the Unicode value of the character at a given index.
Code Example:
javascriptconst str = "Hello, World!";
console.log(str.charAt(0)); // Output: H
console.log(str.charCodeAt(4)); // Output: 111
Explanation:
In the above example, charAt(0)
returns the character at index 0, which is 'H'. charCodeAt(4)
returns the Unicode value of the character at index 4, which is 111.
(Continued...)
0 Comments