String Manipulation in JavaScript

String Manipulation in JavaScript

·

5 min read

For most applications, it's important to be able to store and display massage!

As we learned in the previous lesson we will store these massage in data types called strings. Sometimes, after we store a massage in a string we need to manipulate it in some way.

Let's say we had a looong post and we wanted to show the first 100 characters of a string to a user before they click into it. How could we do this?

We could take a slice of the string from the beginning to the 100th character!

You'll see in this lesson slice is, in fact, a string method

In other cases, we may also want to replace words or escape characters. There are many reasons to edit string! Let's learn about them!

Looking up Characters

In JavaScript, you can look up characters in strings by index. There are two ways to do this: with "charAt" or square brackets "[]"

Let's see some examples:

"Hello".charAt(1);//e
"Hello"[1];//e

In both of these examples, we are looking up character at the 1 index, which turns out to be character e.

Strings use zero-based indexing. This means the index of the first character is 0 and moves up 1 for each subsequent character.

Let' examine some ways to compare strings

Comparing Strings

Comparing string is actually quit simple! We can use the comparison operators we learned about in previous lessons: === , < and >.

For ===, we can do a case-sensitive comparison of the strings to determine if they are the same:

console.log('a'==='a');//true
console.log('a'==='A');//false
console.log('a'===' a');//false

Notice that the comparison is case-sensitive and requires exact equality, including whitespace. We'll learn how to trim white spaces and ignore casing in future exercise.

We can also use > and < to determine if a string comes before another:

console.log('a'>'b');//false
console.log('a'<'b');//true
console.log('abc'<'apple');//true

The string comparison will sort each letter in turn, which is why 'abc' is less than 'apple'

The localeCompare() method returns a number indicating whether a reference string somes before, or after, or is the same as the given string in sort order. IN implementations with Intl.collator API support, this method simply calls Intl.Collator

const a = 'reserve'; 
const b = 'RESERVE'; 

console.log(a.localeCompare(b));
// Expected output: 1
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' }));
// Expected output: 0

Character Casing

Often with strings, we want to ignore the character casing. We want to find "x" whether it is lower-case "x" or upper-case "X".

Fortunately, there are two convenient methods to manipulate casing for a string:

console.log("Hello".toLoserCase());//hello
console.log("Hello".toUpperCase());//HELLO

Notice how these functions will affect the entire string. If we wanted to check if a string said "hello" regardless of its casing we could use either of these functions:

console.log("Hello".toUpperCase()==="HELLO");//true
console.log("Hello".toLowerCase()==="hello");//true

String Length

An important property built-in into strings is length. We can easily look up how many characters are stored in a string by accessing this property:

console.log("a".length);//1
colsole.log("Hello".length);//5

Since the character indexing is 0-based, the length value will actually be 1 greater than the last character index.

This is an important thing to notice for this current task!

String Looping

String are super easy to loop over! We learned about accessing characters using brackets [] and the length property.

So, how can we use these new tool to loop over strings?

const string = "Hello";
for(let i=0; i<string.length; i++){
    console.log(string[i]);
}

What will this log to the console?

It will log: H, e, l, l, o in that order after each iteration

Index of

We learned how to look up a character by index. Now it's time to find the index of a specific string!

There is a method on strings called indexOf that will help us find the first index of a string. Let's see this in action:

"Hello".indexOf("e");//1
"abca".indexOf("a");//0
"abc".indexOf("q");//-1
"happy dog bark".indexOf("dog");//6

We can look up the index of single characters as well as full strings! If the index is not found, indexOf will return a -1.

Although not as often used, it is interesting to note that there is also a lastIndexOf function on strings. This works as expected, it finds the last occurrence of the string and returns its index.

Slicing Strings

Let's learn about another string method: slice!

Slice allows us to pass two parameters: a start index and an end index.

The resulting string will be a sliced string between those two indexes, not including the character located at the end index. Let's see some examples:

"An apple".slice(0,2);//An
"The 40 Thieves".slice(4,8);//40

If the last index is not provided, the slice will continue until the end of the string:

"please slice me".slice(7);//slice me

Slice works with negative arguments too

Negative Arguments

We can also use negative arguments to slic strings starting from the end of the string!

"the apple".slice(-5);//apple
"the apple".slice(-5,-2);//app

We are able to grab the "apple" from the string by starting at the end of the string and going back five character (-5).

Without a second argument, this will return the rest of the string. With a second argument, we can specify up to what point we want to slice the string. In the example we slice up to two characters from the end ( -2).