blog bg

October 24, 2023

JavaScript: Working with Strings

Share what you learn in this blog to prepare for your interview, create your forever-free profile now, and explore how to monetize your valuable knowledge.

String

Strings are useful for holding data that can be represented in text form.

for example,

const airline = "Vargin Airline"
const planeNumber = "VA1230"

So just like in arrays, we can get the character of a string at a certain position.

for example,  get the position 0 of the variable plane Number

const planeNumber = "VA1230"
console.log(planeNumber[0]);//V
console.log(planeNumber[1]);//A
console.log(planeNumber[2]);//1

from the above example position 2 of planeNumber returns 1, however it is still string. So if we want them to be numbers then we will have to convert them. as shown below,

console.log(planeNumber[2]);//1
console.log(typeof planeNumber[2]);//String
console.log(typeof Number(planeNumber[1]));//Number

 

String Length[learn more]

we can also read the the length of string. Just like we can in arrays. we use length to calculate the length of a string. for example,

const planeNumber = "VA1230"
console.log(planeNumber.length);//1

 

String Methods

So again comparing strings to arrays here, strings also have methods and some of them are quite similar to the array methods. Lets have look at some methods

 

indexOf(searchValue, start(optional))[learn more]

By using this method, we can get the position in which a certain letter/word is in the string. for example

const planeNumber = "VA10230"
console.log(planeNumber.indexOf("A"));//1
console.log(planeNumber.indexOf(0));//3

as you can see strings are also zero-based, meaning that their index will start from 0.  Also, indexOf method will only give us the first occurrence. 

NOTE: This is actually case sensitive, which mean that if I search with lowercase, it will search only lowercase even if we have uppercase and if the search does not find then it will return -1. for example,

const planeNumber = "VA10230"
console.log(planeNumber.indexOf("v"));//-1

This method will take two parameters which are searchValue(required): the string to search for and startIndex(optional): The position to start from, the default value is string length

 

lastIndexOf(searchValue, startIndex(optional))[learn more]

By using this method, we will get the position of last occurrence of a certain letter/word in the string. for example,

const planeNumber = "VA10230"
console.log(planeNumber.lastIndexOf(0));//6

NOTE: This method is case sensitive and return -1 if the search does not find

This method will take two parameters which are searchValue(required): the string to search for and startIndex(optional): The position to start from, the default value is string length

Why are these methods useful?

We can use these methods to extract part of a string using the slice method and a slice method needs indexes as arguments and Also sometimes it can be very useful to first figure out the index of part of string to then extract it. So lets see how the slice method works


 Slice(startIndex, endIndex(optional))[learn more]

Basically this method extracts a section of the string and returns it as a new string, without modifying the original string. for example,

const airline = "Vargin Airline"
console.log(airline.slice(4));//in Airline

from above example, 4 is the begin parameter. So basically its the position at which the extraction will start. This does not change the original strings that because it's actually impossible to mutate strings because they are primitive. So if we want to use the sliced String(which will produce a new string) then we will have to store it first into some variable or some data structure.

const airline = "Vargin Airline"
console.log(airline.slice(4,8));//in A

As you can see the above example, end value(8) is actually not included in the string

NOTE: the length of the extracted string is always going to be end minus beginning. So 8 - 4 = 4 => in A(4(i),5(n),6(space),7(A)), This method does not change the original string and returns a new string and a negative number selects from the end of the string.

 

consider following string,

const myself = "I am a Frondend Developer"

1. extract just the first word of the string

here, without knowing any of the indexes and so that's where indexOf and lastIndexOf become really important.

console.log(myself.slice(0, myself.indexOf(" ")));//I

2. extract just the last word of the string

console.log(myself.slice(myself.lastIndexOf(" "),myself.length));//Developer

Also we can even define a negative begin arguments with slice method. So, if the begin augment is positive then extraction will happen from the start . if the begin argument is negative then actually start extracting from the end . For example, 

console.log(myself.slice(2));//am a Frondend Developer
console.log(myself.slice(-2));//er
console.log(myself.slice(1, -1));//am a Frondend Develope

 

EXERCISE: if the string that we receive, contains B or E at the end then, it's a middle seat

const checkMiddleSeat = (seat) => {
  const seatLetter = seat.slice(-1);
  if(seatLetter == "B" || seatLetter == "E"){
    console.log("This is middle seat");
  }else{
    console.log("This is not middle seat");
  }
}

checkMiddleSeat("11B")//This is middle seat
checkMiddleSeat("23C")//This is not middle seat
checkMiddleSeat("3E")//This is middle seat

NOTE: Strings are just primitive and whenever we call a method on a string, JavaScript will automatically behind the scenes, convert that string primitive to a string object with the same content. Then it's on that object where the methods are called. this process is called boxing because it basically takes our string and puts into a box which is the object. 

 

toLowerCase()[learn more]

By using this method, we can change the entire string to lowercase and this function does not require any arguments at all, for example,

NOTE: This method does not change the original string

const myself = "I am a Frondend Developer"
console.log(myself.toLowerCase());//i am a frondend developer

 

toUpperCase()[learn more]

By using this method, we can change the entire string to uppercase and this function does not require any arguments at all, for example,

NOTE: This method does not change the original string

const myself = "I am a Frondend Developer"
console.log(myself.toUpperCase());//I AM A FRONDEND DEVELOPER

Exercise: Make the first character of the word capital and the others will be lowercase,

const name = "joNaThan"
//our target is to change the name to "Jonathan"
const nameLowerCase = name.toLowerCase();
const correctName = name[0].toUpperCase()+ nameLowerCase.slice(1)
console.log(correctName);//Jonathan


trim()[learn more]

By using this function, we can removes the whitespace from both the ends. for example,

const myEmail = "  my-Email@mAil.co  \n"

//our target is to change the myEmail to "my-email@mail.co"
const lowerEmail = myEmail.toLowerCase();
const trimmedEmail = lowerEmail.trim()
console.log(trimmedEmail);//my-email@mail.co

NOTE: This method does not change the original string


trimStart()[learn more]

By using this function, we can removes the whitespace from the beginning of a string

NOTE: This method does not change the original string

 

trimEnd()[learn more]

By using this function, we can removes the whitespace from the end of a string

NOTE: This method does not change the original string

 

replace(searchValue, newValue)[learn more]

one of the most important thing about string, which is to replace parts of string. for example,

const myself = "I am a Frontend Developer"
console.log(myself.replace("Frontend","Backend"));//I am a Backend Developer
const price = "288,97£"
//expected output "288.97$"
console.log(price.replace("£","$").replace(",","."));//288.97$

This method will take two parameters which are searchValue(required): the value/ regular expression, to search for and newValue(optional): The new value to replace with 

NOTE: This method does not change the original string and returns a new string with the value(s) replaced

 

replace() will only replace the first occurrence of this search string. For example,

const price = "Please move from door 1 to door 3"
//expected output "288.97$"
console.log(price.replace("door","gate"));//Please move from gate 1 to door 3

However, if we want to replace all the  occurrence of the search string with replace()

const price = "Please move from door 1 to door 3"
console.log(price.replace(/door/g,"gate"));//Please move from gate 1 to gate 3

 

replaceAll(searchValue, newValue)[learn more]

replace the all the occurrence of this search string . For example, 

const price = "Please move from door 1 to door 3"
console.log(price.replaceAll("door","gate"));//Please move from gate 1 to gate 3

NOTE: This method does not change the original string and returns a new string with all values replaced

 

Methods that return Boolean.

 

includes(searchValue,startIndex(optional))[learn more]

This method will return true if a string contains a specific string. Otherwise it returns false. for example,

NOTE: This method is case sensitive

const title = "Javascript is fun";
console.log(title.includes('is'));//true
console.log(title.includes('is not'));//false

This method will take two parameters which are searchValue(required): The string to search for and startIndex(optional): The position to start from, the Default value is 0


startsWith(searchValue,startIndex(optional))[learn more]

This method will return true if the string start with the value. Otherwise it returns false. for example,

NOTE: This method is case sensitive

const title = "Javascript is fun";
console.log(title.startsWith('Java'));//true
console.log(title.startsWith('java'));//false

This method will take two parameters which are searchValue(required): The string to search for and startIndex(optional): The position to start from, the Default value is 0


 endsWith(searchValue,length(optional))[learn more]

This method will return true if the string ends with the value. Otherwise it returns false. for example,

NOTE: This method is case sensitive

const title = "Javascript is fun";
console.log(title.endsWith('fun'));//true
console.log(title.endsWith('Fun'));//false

This method will take two parameters which are searchValue(required): The string to search for and length(optional): The length of the stringto search, the Default value is the length of the string

So whenever we need to take some decision based on the contents of the string, these three methods are helpful

 

Split(seperator,limit)[learn more]

This method allows us to split a string into multiple parts based on a divider string. for example,

NOTE: This method does not change the original string

const title = "Javascript*is*fun";
console.log(title.split('*'));//[ 'Javascript', 'is', 'fun' ]

As you can see from above example, when we call split method on string title, we specify a divider called * and now it will split up this string by this * and then it will then store the results into elements of a new array. 

Let's have a look at some examples,

  • Extract firstName and LastName from the fullName(heath Herndron)
const fullName = "Heath Herndron";
const [firstName, lastName] = fullName.split(" ")
console.log(firstName);//Heath
console.log(lastName);//Herndron
  • make sure that first letter of firstName and LastName is capital
const fullName = "heath herndron";
const [firstName, lastName] = fullName.split(" ")

console.log(firstName);//heath
console.log(lastName);//herndron
console.log(firstName.replace(firstName[0],firstName[0].toUpperCase()));//Heath
console.log(lastName.replace(lastName[0],lastName[0].toUpperCase()));//Herndron

This method will take two parameters which are seperator(optional): The string or regular expression to use for splitting and limit(optional): An integer that limits the number of splits, items after the limit are excluded


Padding A String

It means that adding a number of characters to  the string until the string has a certain desired length. There are two methods to accomplish this,

 

padStart(length,string(optional))[learn more]

By using this method, add some characters to the beginning of the string until it reaches a given length. First argument is the length that we want for a string and the other argument is the character that we want to pad the string with. for example,

let numString = '25';
console.log(numString.padStart(5,0));//00025

This method will take two parameters which are length(required): The length of the resulting string and string(optional): The string to pad with and default is space

NOTE: This method is a string method. So to pad a number,convert the number to a string first

 

padEnd(length,string)[learn more]

By using this method, add some characters to the end of the string until it reaches a given length. First argument is the length that we want for a string and the other argument is the character that we want to pad the string with. for example,

let numString = '25';
console.log(numString.padEnd(5,0));//25000

for example, 

usually when we see a credit card number on the internet, you never see the entire number and the rest is marked with some symbol, let's do this

const formattedCreditCard = (card) => {
  const cardString = String(card);//convert number to string
  let lastFourDigit = cardString.slice(-4);
  return lastFourDigit.padStart(cardString.length,'*')
}

let maskedCardNumber = formattedCreditCard(4232543465433454);
console.log(maskedCardNumber);//************3454

This method will take two parameters which are length(required): The length of the resulting string and string(optional): The string to pad with and default is space

NOTE: This method is a string method. So to pad a number, convert the number to a string first

 

repeat(count)[learn more]

This method allows us to repeat the same string multiple times.

NOTE: This method does not change the original string and returns a new string

for example,

const message = "Welcome to Terminal Two.."
console.log(message.repeat(3));//Welcome to Terminal Two..Welcome to Terminal Two..Welcome to Terminal Two..

This method will take one parameter which is length(required): The number of copies

Next Article: JavaScript: Working with Functions

496 views

Please Login to create a Question