String Methods in JavaScript

String Methods in JavaScript

In today's article, I would be explaining String Methods. I'm sure we all know what strings are. Just to refresh our memories; Strings are texts that help in holding data that can be represented. Strings can store characters like "User". A string can be any text inside a single or double quote. It will also be good to note that the first character in a string begins with a position of 0. This is known as the String Index.

What are String Methods?

Now, what are Methods? Methods are built-in actions we can perform with individuals strings. These methods and properties can be found in the Chrome dev tools.

To understand how the string methods can be used, below is a syntax:

variableName.Method()

Here we have our string variable connected to a dot with the desired method and then a parenthesis.

EXAMPLES OF STRING METHODS

There are many string methods but I would be explaining a few. Below are some examples:

  • trim(): It removes any whitespace at the beginning or end of a string.
const name = "   Flora Badmus       ";
console.log(name.trim()); // returns "Flora Badmus"
  • slice(): It extracts a part of a string and returns a new string. This involves the index at which to start extracting and the index at which to stop extracting.
const address = "No 10 Downing Street";
console.log(address.slice(6, 20)); // returns "Downing Street"
  • repeat(): It creates a new string by repeating the given string a specified number of times and then returns it.
const userName = "John Doe";
console.log(userName.repeat(2)); // returns "John DoeJohn Doe"
  • indexOf(): It returns the index position of the first occurrence of a value in a string.
const bookTitle = "A Book for the Youth written by the Youth";
console.log(bookTitle.indexOf("Youth")); // returns 15
  • toLowerCase(): It returns a version of that string in lowercase.
const fullName = "FEMI GBADEBO";
console.log(fullName.toLowerCase()); // returns "femi gbadebo"
  • toUpperCase(): It returns the string in uppercase.
const fullName = "femi gbadebo";
console.log(fullName.toUpperCase()); // returns "FEMI GBADEBO"
  • You can also combine string methods. This works from left to right.
const userName = "John Doe       ";
console.log(userName.trim().toUpperCase()); // returns "JOHN DOE"

Note: The original string remains unchanged in all cases.