In this article, we’ll look at some of the common ways to work with JavaScript strings!

This follows on from my previous post: The Basics of JavaScript Strings, be sure to check it out if you haven't already!

The Anatomy of a String

Each character in a string is numbered, starting at 0. For example:

"This is my string!"   

The first character is T at index position 0.

The last character is ! at index position 17.

The spaces also have index positions at 47 and 10.

We can access any character like so:

"This is my string![8]"     // m

charAt()

We can similarly use the charAt() method. It returns the character at the specified index in a string, such as:

"This is my string!.charAt(8)"     // m

indexOf()

We can use indexOf() if we wish to return an index number.

It returns the index of where the substring starts in the string, or -1 if the substring isn’t found. It’s case-sensitive.

const str = "This is my string!";

str.indexOf('s');       // returns 3 (the first 's' instance)

str.indexOf('my');      // returns 8

str.indexOf('My');      // returns -1

str.lastIndexOf('s');   // returns 11 (the last instance)

You can use a conditional to test if a substring exists:

if (str.indexOf('my') > -1) {
	console.log('Success! It contains the string');
}

This works as we know that -1 results when nothing is found, so logically any result greater than -1 would mean the substring exists.

slice()

To get a portion of a string starting (and optionally ending) at a particular character, we can use slice().

This method can take 2 arguments. The first is the start position (0 is of course the first character), and the second optional argument is the end position. If either argument is a negative number, it will start at the end of the string and work backward.

const str = "This is my string!";

str.slice(5);         // "is my string!"
str.slice(5, 10);     // "is my"
str.slice(0, -8);     // "This is my"

Finding the Length of a String

To find the length of a string we can use the length property. It returns the number of characters in a string.

"This is my string!".length;     //18

The length property returns the actual number of characters starting with 1, which in our example is 18, not the final index number, which starts at 0 and ends at 17.

Converting to Upper or Lower Case

The two methods toUpperCase() and toLowerCase() are useful ways to format our text.

toUpperCase()converts all text in a string to uppercase.

const str = "This is my string!";
const upper = str.toUpperCase();
console.log(upper);

// "THIS IS MY STRING!"

toLowerCase()converts all text in a string to lowercase.

const str = "This is my string!";
const lower = str.toLowerCase();
console.log(lower);

// "this is my string!"

split()

To divide a string up into sections & insert the contents into an array, we can use the split() method.

The argument we provide is the delimiter, the character that we’re using to split up our string.

In the below example, let's use the whitespace “ “ character as our delimiter:

const str = "This is my string!";
const splitString = str.split(" ");

console.log(splitString);

// ["This", "is", "my", "string!"]

We can now access each section via its array position..

splitSting[0];    // This
splitSting[1];    // is
splitSting[2];    // my
splitSting[3];    // string!

We can also optionally provide a second argument to stop splitting a string, after a certain number of delimiter matches have been found.

Let's look at another example, this time using a comma ‘, ‘ as our delimiter.

const shoppingList = 'Bananas, green apples, chocolate, cat food';
const foodItems = shoppingList.split(', ');
console.log(foodItems);

// ["Bananas", "green apples", "chocolate", "cat food"]

const snacks = shoppingList.split(', ', 2);
console.log(snacks)

// ["Bananas", "green apples"]

Our .split(', ', 2) stopped the split after the second comma, returning just the first two array entries.

trim()

The trim() method removes any white space from both ends of a string, but importantly not anywhere in between.

const ahhhhWhitespace = "     This is my string!     ";

const trimmed = ahhhhWhitespace.trim();

console.log(trimmed);

// "This is my string!"

Whitespace can be tabs or spaces, the trim() method conveniently removes any excess.

replace()

If we wish to search through a string for a value, and replace it with a new value, we use replace().

The first parameter will be the value to find, and the second will be the replacement value.

const str = "This is my string!";

const newString = str.replace("my", "your");

console.log(newString);

// This is your string!

By default, the replace() method replaces the first match only. To replace all matches, you’ll need to pass in a regular expression using the global flag g. If we also want to ignore case, we’d add the case insensitive flag i.

const str = "GOOGLE is my homepage. But I don't use Google Chrome."

const newString = str.replace(/google/gi, "Google");

console.log(newString);

// Google is my homepage. But I don't use Google Chrome.

Here we’re telling every instance of google within our string (regardless of case), to be replaced by “Google”.

Converting Strings into Numbers

In this final section, let's take a quick look at some of the ways we can convert strings into numbers.

parseInt()

To convert a string into an integer (a whole number) we can use parseInt(). It takes two arguments, the first being the value we want to convert, and the second is called the radix. This is the base number used in mathematical systems. For our use, it should always be 10, the decimal system.

parseInt('64', 10);     // 64

parseInt('64.9', 10);   // 64

parseInt('64px', 10);   // 64

parseFloat()

If we wish to convert into a floating-point number (a number with decimal points), we’d use parseFloat().

parseFloat('64.9');             // 64.9

parseFloat('64bit');            // 64

console.log(parseFloat('64'));  // 64

Number()

We can convert our strings with the Number() method as well, however, it's stricter about which values it can convert. It only works with strings that consist of numbers.

Number('64');      // 64

Number('64.9');    // 64.9

Number('64bit');   // NaN

Number('64%');     // NaN

NaN if you recall — stands for Not a number.

Related Posts: