How to Use String Functions in JavaScript?

Estimated read time 2 min read

JavaScript provides several built-in string functions for manipulating strings. Here are a few of the most commonly used string functions:

  1. length: Returns the length of a string.
let str = "Hello, World!";
console.log(str.length); // Output: 13
  1. concat: Joins two or more strings and returns a new string.
let str1 = "Hello, ";
let str2 = "World!";
let str3 = str1.concat(str2);
console.log(str3); // Output: "Hello, World!"
  1. charAt: Returns the character at a specified index in a string.
let str = "Hello, World!";
console.log(str.charAt(0)); // Output: "H"
  1. indexOf: Returns the first index at which a given element can be found in the string, or -1 if it is not present.
let str = "Hello, World!";
console.log(str.indexOf("o")); // Output: 4
  1. slice: Extracts a section of a string and returns a new string.
let str = "Hello, World!";
console.log(str.slice(7, 13)); // Output: "World"
  1. replace: Replaces the first match of a string or a regular expression with a replacement string.
let str = "Hello, World!";
console.log(str.replace("World", "Friend")); // Output: "Hello, Friend!"
  1. toUpperCase and toLowerCase: Converts a string to all upper case or all lower case letters.
let str = "Hello, World!";
console.log(str.toUpperCase()); // Output: "HELLO, WORLD!"
console.log(str.toLowerCase()); // Output: "hello, world!"

These are just a few of the most commonly used string functions in JavaScript. You can find more information on the available string functions in the JavaScript documentation.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply