Trey Huffine has a pretty good blog post about string methods published recently. But all the code samples are alt-text-missing images. I figured I'd re-create a version of it with live samples so it might be easier to reference. Check out Trey's post for more examples and written explaintions of each method!

.length

  const str = "This little piggy went to market.";
console.log(str.length);
// 33

.trim

  let str = '  Chris Coyier   ';
console.log(str, str.length); // 17
str = str.trim();
console.log(str, str.length); // 12

.includes

  let str = "Chris Coyier";
const searchTerm1 = "Chris";
const searchTerm2 = "Wanda";
console.log(str.includes(searchTerm1)); // true
console.log(str.includes(searchTerm2)); // false

.indexOf

  const str = "xxxxxDOGxxxxx";
const searchTerm = "DOG";
console.log(str.indexOf(searchTerm)); // 5
console.log(str.indexOf("x")); // 0

.toUpperCase

  let str = "i don't wanna grow up.";
str = str.toUpperCase();
console.log(str); // "I DON'T WANNA GROW UP."

.toLowerCase

  let str = "UP and DOWN and UP and DOWN."
str = str.toLowerCase();
console.log(str); // "up and down and up and down."

.replace

  let str = "<p>Testing</p>";
str = str.replace("<p>", "");
console.log(str); // "Testing</p>"
str = str.replace(/<\/p>/gi, "!");
console.log(str); // "Testing!"

.slice

  let str = "Name: Chris";
str = str.slice(6);
console.log(str): // Chris

  let str = "Name: Chris";
let br = str.indexOf(":");
str = str.slice(br + 1).trim();
console.log(str); // Chris

  let str = "Name: Chris";
str = str.slice(-1);
console.log(str); // s

.split

  str = "Chris John Coyier";
let split = str.split(" ");
console.log(split); // ["Chris", "John", "Coyier"]

.repeat

  let str = "la ti da ";
str = str.repeat(4).trim();
console.log(str); // "la ti da la ti da la ti da la ti da"

.match

  let str = "Chris Coyier";
let matches = /Chris/g;
let found = str.match(matches);
console.log(found); // ["Chris"]

matches = /[A-Z]/g;
found = str.match(matches);
console.log(found); // ["C", "C"]

.charAt

  let str = "Zebra";
console.log(str.charAt(0)); // Z
console.log(str.charAt(str.length - 1)); // a

.charCodeAt

  let str = "AB 💩";
console.log(str.charCodeAt(0)); // 65
console.log(str.charCodeAt(1)); // 66
console.log(str.charCodeAt(3)); // 55357


4,388 2 42