DEV Community

Cover image for Some JavaScript string methods and how to use them
Emmanuel Aiyenigba
Emmanuel Aiyenigba

Posted on • Updated on

Some JavaScript string methods and how to use them

Last time I wrote an article about JavaScript array methods, explaining what each method does and how to use them in your project (since we all have to deal with Arrays everyday of our developer lives, right?).

Today, you will be learning about string methods in JavaScript and how you can use them effectively in your project.

string methods

Strings? What are those?

A string is a collection of one or more characters, which can include letters, numbers, or symbols. Strings are immutable in JavaScript(they simply cannot change unlike in C programming language). Strings are primitive data types. Other primitive data types are: Null, Undefined, Boolean, Number, BigInt and Symbol.

There are about 24 string methods in JavaScript. In this post, you shall be learning how to work with a few of them( I want to wet your appetite with those few so you can be hungry to go check out the other methods yourself... huh!)

What are string methods

When you work with strings in your project, more often than not, you want to manipulate them. Methods are built in functions that help us carry out manipulations on your string.

Let's dive right in to see how we can use some of this methods to make our string input what we want it to be for our application to scale.

charAt()

charAt() is used to get the character at a particular position in a string. Yeah, that's it!

const name = "EmmanuelTheCoder"
const letter = name.charAt(0);

console.log(letter)
//result: E

Enter fullscreen mode Exit fullscreen mode

We specified that we want the character at position zero and we got "E".

What if I specify a position that doesn't exist on the string?

Don't worry, JavaScript won't yell at you, it will only return a whitespace instead of any value.

You can always use String.length to get the length of your string and know what the last position will be.

I'm sure you now understand this method. Now, unto the next!

charCodeAt()

This method returns the Unicode of the character at the specified position.

Hey, hey, hey! slow down a moment. What the hell is a Unicode?
Hehehe. Not the hell. A Unicode is an international encoding standard by which each letter, digit, or symbol is assigned a unique numeric value.

Suffice to say, every letter, digit or symbol has an assigned unique numeric value.

You will see for yourself in a moment.


const name = "EmmanuelTheCoder";

const numVal = name.charCodeAt(0);

//we are simply saying what is the
// assigned encoding value for "E"

console.log("Unicode of 'E' is:" numVal)
//result: 69

Enter fullscreen mode Exit fullscreen mode

But what if the position I specified in the method does not exist in the string?

Unlike charAt(), charCodeAt() is not going to forgive you by returning an empty space. It will yell NaN at you!

endsWith()

This is used to check if a string ends with a specified value. It returns a Boolean.

const title = "EmmanuelTheCoder is a developer"
const lastWord = title.endsWith("developer")

console.log(lastWord)

//result: true

Enter fullscreen mode Exit fullscreen mode

The endsWith() method takes in two parameters: the first is the value you want to check and the second, which is optional, is the length of the string to search

const title = "EmmanuelTheCoder is a developer"
const lastWord = title.endsWith("developer",10)

console.log(lastWord)

//result: false

Enter fullscreen mode Exit fullscreen mode

It returned false because the word "developer" cannot be found at the end of the first 10 letters.

Got this? Yeah, let's proceed to the next method

fromCharCode()

This method convert Unicode value to string. It's like the opposite of charCodeAt()

Let's see in code how it works.

const letter = String.fromCharCode(72);

console.log(letter);

//result: "H"
Enter fullscreen mode Exit fullscreen mode

This is to say the string equivalent of the Unicode value 72 is "H".

includes()

This method checks if a string includes a particular value. It returns a Boolean

const profile = "EmmanuelTheCoder is a developer from Africa"
const continent = profile.includes("Africa")
console.log(continent)
//result: true
Enter fullscreen mode Exit fullscreen mode

The includes() method can also take a second parameter (which is optional) to specify the position where the check is to begin.

indexOf()

This is used to get the position of the first occurrence of a value in a string.

const profile = "EmmanuelTheCoder is a developer from Africa and lives in Africa"

const checkContinentPostion = profile.indexOf("Africa")

console.log(checkContinentPostion)
//result: 37

Enter fullscreen mode Exit fullscreen mode

checkContinentPosition returns the first occurrence of Africa in the string.

If the value is not found in the string, it returns -1. You can also specify the position to start the search from as the second parameter.

lastIndexOf()

If you need to get the last occurrence of a value in a string, then this your go to method.
Now let's search the last occurrence of Africa.

const profile = "EmmanuelTheCoder is a developer from Africa and lives in Africa"

const checkLastOccurenceOfAfrica = profile.lastIndexOf("Africa")

console.log(checkLastOccurenceOfAfrica)
//result: 57

Enter fullscreen mode Exit fullscreen mode

This method could also take in a second parameter as the position to start the search from.

localeCompare()

It compares two strings in the current locale and returns:

-1 if the string is sorted before the compared string
0 if the two strings are equal
1 if the string is sorted after the compared string.

const text1 = "ab"
const text2 = "cd"

const compare = text1.localCompare(text2)

//result: -1
Enter fullscreen mode Exit fullscreen mode

match()

This method is used to search for a value in a string. Depending on what you want to achieve, it's best to pass in a regular expression as the parameter for a better search

const sentence = " I say if you will STAY in the house, you have to pay. Okay?"

const searchAValue = sentence.match(/ay/g);

console.log(searchAValue)
//result: ['ay', 'ay', 'ay']

Enter fullscreen mode Exit fullscreen mode

It return an array with the matches. You can convert this array to a string by doing searchAValue.toString(). toString() is another method that is used to convert a non-string to a string.

You will observe that, the search didn't return all our matches. This is because we didn't specify in regular expression that the global search should be case-insensitive hence the reason why the search omitted the "ay" in "STAY". Let's do that now.

const sentence = " I say if you will STAY in the house, you have to pay. Okay?"

const searchAValue = sentence.match(/ay/gi);

console.log(searchAValue)
//result: ['ay', 'AY' 'ay', 'ay']

Enter fullscreen mode Exit fullscreen mode

Did I hear you say whoa whoa whoa! could you slow down a minute for me to get all this stuff?
Oh, yeah I will. Let's just do one more method and I promise to pause so that you can go practice them. Deal? Yeah!

Okay let's trim this down. hehehe!

trim()

This method is used to remove all whitespaces from both side of a string. Note that, it remove spaces from both sides and not from in-between the string.

const followMeOnTwitter = "   @EmmanuelCoder"
const followMePlease = followMeOnTwitter.trim()

console.log(followMePlease)
//result: '@EmmanuelCoder'

Enter fullscreen mode Exit fullscreen mode

Hurrayyyyyy! You made it to this point, congratulations! Please go and practice more so that you can master how to manipulate strings.

Kindly give this post a like and also share!

Oldest comments (4)

Collapse
 
curiousdev profile image
CuriousDev

Thank you, I usually like to learn about standard functions of JS! These can be useful many times.

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba

I'm glad you found this useful.

Collapse
 
astronika profile image
Bożena Pięta

localeCompare() not localCompare()

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba

Oops, that was an oversight. Thanks for pointing it out.