String Manipulation (lastIndexOf, Slice, Replace) with examples :>
Today we are going to learn some basic string manipulation methods that can really help you to change your string according to your application requirements.
Let’s start with Splice() : it helps you to splice (a piece of string/character) from your provided variable.
Basic Syntex: splice(from -to)
let first= string.splice(0,5) , => it means that store the first 5 character of provided string into first name variable.
lastIndexOf()
It helps you to find the last value in the provided string, it searches the string from end to beginning it’s case sensitive and returns a -1 value if the value isn’t found.
let text= “ I live in Pakistan”
let newString=text.lastIndexOf(“Pakistan”);
which will return 11 as the counting beginning from 0 taking empty space also into consideration.
Replace()
As the name says replace() method replace your provided character with the defined character.
let ch=” I love Apple Laptops”
let chNew=ch.replace(“Apple” , “Lenovo”);
now the value gets updated with: I love Lenovo update.
And if you want to replace one string multiple times you can use /”string”/g * where g stands for global.
let text = “I love to play Cricket, because Cricket is very good physical sport”;
let newText= text.replace(/Cricket/g, “Football”);
I know you are getting bored so let’s end this by practicing a real-life application.
Suppose you are asked to split and store name and email domain into variables how you will do this?
Here’s how
let Email: Hamza@Gmail.Com
(1) Splitting name from ‘Hamza@Gmail.Com’
let name=email.slice(0, email.lastIndexOf(“@”));
which returns: Hamza
(2) Splitting Domain Name
let domain=slice.Email(lastIndexOf(“@”)+1, Email.length);
It will return = Gmail.com
I hope you understand these basic foundation concepts if you have any questions let me know in the comment if you like the content give a thumbs-up.