5 string methods in JavaScript.

November 27, 2020#javascript

Strings are useful for holding data that can be represented in text form, and here's 5 methods for them.

1. includes()

includes() method determines whether one string may be found within another string, returning true or false.

const sentence = "The quick brown fox jumps over the lazy dog.";

const word = "fox";

console.log(
  `The word "${word}" ${
    sentence.includes(word) ? "is" : "is not"
  } in the sentence.`
); // The word "fox" is in the sentence.

2. replace()

replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If pattern is a string, only the first occurrence will be replaced.

const p =
  "The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";
const regex = /dog/gi;

console.log(p.replace(regex, "ferret")); // The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?

console.log(p.replace("dog", "monkey")); // The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?

3. split()

split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array.

const str = "The quick brown fox jumps over the lazy dog.";

const words = str.split(" ");
console.log(words[3]); // fox

const chars = str.split("");
console.log(chars[8]); // k

4. startsWith()

startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

const str = "Saturday night plans";

console.log(str.startsWith("Sat")); // true

5. trim()

trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

const greeting = "   Hello world!   ";

console.log(greeting); // "   Hello world!   "
console.log(greeting.trim()); // "Hello world!"