How to Use String Properties in JavaScript?

Estimated read time 2 min read

In JavaScript, strings have properties and methods that can be used to manipulate and get information about them.

Here are some common string properties and methods that you can use in JavaScript:

Properties:

  • length: Returns the length of the string.

Methods:

  • charAt(index): Returns the character at the specified index in the string.
  • concat(string1, string2, ...): Combines two or more strings into a single string.
  • indexOf(searchValue, [startIndex]): Returns the index of the first occurrence of a specified value in a string, starting from the specified index.
  • lastIndexOf(searchValue, [startIndex]): Returns the index of the last occurrence of a specified value in a string, starting from the specified index.
  • slice(startIndex, [endIndex]): Extracts a section of a string and returns it as a new string.
  • substring(startIndex, [endIndex]): Returns a part of a string between two specified indices.
  • toLowerCase(): Converts all uppercase characters in a string to lowercase.
  • toUpperCase(): Converts all lowercase characters in a string to uppercase.
  • trim(): Removes whitespace from both sides of a string.

Here’s an example of how you can use these properties and methods in JavaScript:

let str = "Hello, World!";

console.log("The length of the string is: " + str.length);
console.log("The character at index 0 is: " + str.charAt(0));
console.log("The combined string is: " + str.concat(" How are you?"));
console.log("The index of 'l' is: " + str.indexOf("l"));
console.log("The last index of 'l' is: " + str.lastIndexOf("l"));
console.log("The sliced string is: " + str.slice(7, 12));
console.log("The lowercase string is: " + str.toLowerCase());
console.log("The uppercase string is: " + str.toUpperCase());
console.log("The trimmed string is: " + str.trim());

This would output:

The length of the string is: 13
The character at index 0 is: H
The combined string is: Hello, World! How are you?
The index of 'l' is: 2
The last index of 'l' is: 9
The sliced string is: World
The lowercase string is: hello, world!
The uppercase string is: HELLO, WORLD!
The trimmed string is: Hello, World!

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply