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Ā 4,Ā 7Ā 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:


Tim profile image

A little about me..

Hey, Iā€™m Tim! šŸ‘‹

Iā€™m a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out myĀ Complete Guide to Freelancing if you'd like to find out more.

While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.

Thanks for reading! šŸŽ‰