String Properties And Methods In JavaScript

Strings are an integral part of programming, and are used everywhere from displaying messages to parsing text data.

JavaScript provides us with a variety of built-in tools that we can use to manipulate strings as part of creating programs.

These tools are known as properties and methods, and in this lesson we'll explore some of the more common properties and methods that you're likely to encounter as a beginner.

We'll cover:

Properties and methods

Understanding string properties and methods can significantly improve your ability to manipulate text effectively.

In JavaScript, almost everything is an object under the hood, even strings! Every string has a set of properties and methods attached to it that can be called.

String properties

JavaScript strings come with built-in properties that describe or provide information about the string.

length

The most important string property that you're likely to come across and need to use as a beginner is length.

The length property counts the number of characters in a string, including spaces, punctuation, and special characters:

let message = "Hello, Middle Earth!";
console.log(message.length); // 20

It's particularly useful for validation or processing text dynamically. For example, when creating a form, you might want to restrict usernames to 10 characters:

let username = "FrodoBaggins123";

if (username.length > 10) {
    console.log("Username is too long.");
} else {
    console.log("Username accepted.");
}

String methods

In programming, a method is simply a function that is associated with an object.

Every string that you create has a predefined set of methods that you can call in order to carry out specific functionality. This could be, for instance, querying the data within that string, or performing some kind of manipulation to it.

In this section we'll explore some of the more common methods in depth.

toUpperCase and toLowerCase

These methods convert a string to uppercase or lowercase, respectively.

They're frequently used for normalization i.e. ensuring text follows a uniform case for comparisons.

const greeting = "Hello, Middle Earth!";

console.log(greeting.toUpperCase()); // HELLO, MIDDLE EARTH!
console.log(greeting.toLowerCase()); // hello, middle earth!

They are extremely useful for case-insensitive comparisons, as well as formatting user input such as email addresses:

let email = "FrodoBaggins@BagEnd.Com";

if (email.toLowerCase() === "frodobaggins@bagend.com") {
    console.log("User is valid");
}

indexOf

This method searches for the first occurrence of a substring and returns its position.

If the substring isn’t found, it returns -1.

const sentence = "One does not simply walk into Mordor!";

console.log(sentence.indexOf('simply')); // 13
console.log(sentence.indexOf('Mordor')); // 30

substring

substring() extracts part of a string based on a given index. It's primarily used when working with known positive indices.

const sentence = 'One does not simply walk into Mordor!';

console.log(sentence.substring(13)); // simply walk into Mordor!

It also takes an optional ending parameter:

const sentence = 'One does not simply walk into Mordor!';

console.log(sentence.substring(13, 24)); // simply walk

split

The split() method divides a string into an array of substrings. It accepts a parameter known as a separator that defines where to split.

In the below example we're using a space " " character to separate all of the individual words in the sentence:

const sentence = 'One does not simply walk into Mordor!';

console.log(sentence.split(" ")); // ['One', 'does', 'not', 'simply', 'walk', 'into', 'Mordor!'];

Similarly, you could split every letter by passing in an empty string:

const location = 'Mordor';

console.log(location.split('')); // ['M', 'o', 'r', 'd', 'o', 'r']

trim

The trim() method removes whitespace from the beginning and end of a string:

let username = '  gandalfthewhite   ';

console.log(username.trim()); // gandalfthewhite

This can be particularly helpful for cleaning up user input in forms.

includes

The includes() method can be used to check if a string contains a specific substring. It returns true or false.

const name = 'Frodo Baggins';

console.log(name.includes('Baggins')); // true
console.log(name.includes('Gamgee')); // false

concat

The concat() method (short for concatenate) combines two or more strings into a single string:

let wizard = 'Saruman';
let colour = 'White';

console.log(wizard.concat(" the ", colour)); // Saruman the White

Chaining methods

It's worth noting that JavaScript allows you to chain multiple string methods together using dot notation.

For example, let's say we had a comma-separated list of users, and we wanted to generate an array of these users in lowercase:

const users = 'Frodo, Samwise, Merry, Pippin';

console.log(users.toLowerCase().split(', ')); //  ['frodo', 'samwise', 'merry', 'pippin']

In this example we're chaining together the toLowerCase() and split() methods to create the result we're looking for.

Summary

In this lesson you learned the fundamentals of built-in properties and methods in JavaScript, as well as the essential string properties and methods that you're likely to come across as a beginner.