String Methods

Strings Methods

JavaScript provides several string methods.

We can use these methods with:

  • a period (the dot operator)
  • the name of the method
  • opening and closing parentheses
"example string".methodName();

Some common methods & properties:

  • length: returns the length of the string.
  • toUpperCase(): transforms characters into uppercase.
  • toLowerCase(): transforms characters into uppercase.
  • substring(start, end): extracts the characters from a string between “start” and “end”, not including “end” itself.
  • split(): split a string into an array.

Note: Property like length doesn’t have a parenthesis.

Example

let str = "Hello World";

console.log(str.length); // 11
console.log(str.toUpperCase()); // HELLO WORLD
console.log(str.toLowerCase()); // hello world
console.log(str.substring(0, 5)); // Hello
console.log(str.split("")); // ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]

We can also tag on other methods as well.

let str = "Hello World";

console.log(str.substring(0, 5).toLowerCase()); // hello

String Concatenation:

We can use the + operator to concatenate strings.

console.log("Hello" + " " + "World");
// Hello World

However, we should use template strings when building up strings. For example:

const name = "Jane";

// Concatenation
console.log("My name is " + name);

// Template string
console.log(`My name is ${name}`);