Ticker

6/recent/ticker-posts

JavaScript - String Methods

JavaScript - String Methods

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:

  1. length - Finding the Length of a String
  2. toUpperCase() and toLowerCase() - Converting Case
  3. charAt() and charCodeAt() - Accessing Characters
  4. concat() - Concatenating Strings
  5. slice() - Extracting a Substring
  6. indexOf() and lastIndexOf() - Searching for Substrings
  7. replace() - Replacing Substrings
  8. split() - Splitting a String into an Array
  9. trim() - Removing Whitespace
  10. startsWith() and endsWith() - Checking Start and End
  11. substring() and substr() - Extracting Substrings

1. length - Finding the Length of a String:

The length property returns the number of characters in a string.

Code Example:

javascript
const 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:

javascript
const 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:

javascript
const 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...)

Post a Comment

0 Comments