Javascript
JavaScript Fundamentals -- Strings, Numbers, & Dates
  •  

Working with Strings

PRO

Once you've created a string in JavaScript, there are many methods that can be run on the string. In this video, you'll see two examples of methods that you can run. First is the slice method, which returns a substring of the original string.

const name = 'Preston';
console.log(name.slice(0, 4)); // Pres

This method takes a startIndex and an endIndex, and it returns the characters between those two indexes, stopping at the character before the endIndex.

Another example is split, which breaks a string up into different pieces every time it finds the character you provide. It returns the resulting pieces in an array.

const phone = '888-111-2222;
console.log(phone.split('-')); // ['888', '111', '2222']

In this example we told JavaScript to break the phone string into pieces every time it sees the dash character. The result is an array with three pieces.

There are many string methods you can use. Click here to see a list of all of them.

Template strings are another great part of JavaScript. They're functionally the exact same as normal strings in JavaScript, but they're defined with backticks instead of single or double quotes. The great part is that any JavaScript variable or expression can be injected right into the string.

const name = 'Preston';
console.log(`Hello there, ${name}!`); // Hello there, Preston!

As you can see, there are no addition signs, which are necessary for string concatenation. All you have to do is wrap the variable or expression in curly brackets with a dollar sign out front for it to work. Template strings are much easier than concatenation.

You can follow along with this section by forking this StackBlitz project.