Mastering JavaScript's String Data Type and Its Array of Dynamic Methods for Effective Programming
Mastering the Art of JavaScript Strings: A Deep Dive into String Manipulation
Introduction
As a developer, I can not think of a moment I did not have to use a string in my program. They range in a variety of use cases.
1. names
2. emails
3. passwords
5. variable names
6. sentences
7. and many more use cases.
This article will look at how we use them in JavaScript and their methods.
So let's tighten our seat belts and try as much to get the best out of this.
Question
Can you think of a point in your application where you did not have to use a string to complete a task?
Please leave your answer in the comment section, I will try as much as possible to respond.
Declaration and definition of strings.
There are three ways a string can be expressed.
1. single quote
2. double quotes
3. backticks
const singleQuote = 'My name is Rashid ';
const doubleQuotes = "And I love to code";
const backTicks = `I also love to share my knolwedge
with others.`
// if you want to have a multiple line strings, it's best to use backticks
// you could add them too use a plus operator.
console.log(singleQoute + doubleQoutes)
// "My name is Rashid And I love to code"
To determine the length of the string, utilize the length attribute.
Const stringLength = "Hello World"
console.log(stringLength.length)
// prints 11
String iteration.
Just like an array, Strings are iterable.
const singleQuote = 'My name is Rashid';
for(const char of singleQuote) console.log(char);// Yes you can do it with out brackets.
// prints
//M
//y
//etc
// So spaces in strings are considered as characters.
String Methods.
charAt() , at() and charCodeAt()
// charAt(), at() and charCodeAt() take in an index //of a character instring Const textString = "Hello World" console.log(textString.charAt(0); // prints H // it prints "" if the index is out of bounds/range console.log(textString.charAt(20); // prints "" console.log(textString.at(1)) //prints e // Every character has it's ascii code that uniquely identifies it. // it helps one to know what they are dealing with either // lowercase or uppercase characters characters. // So charCodeAt() will help us find there code. console.log(textString.charCodeAt()) // prints 72
concat()
// This method joins to strings together into one const str = "Hello " const str2 = "World" console.log(str.concat(strs)) // prints Hello World
indexOf() and lastIndexOf()
//These will return the first index of the required word or text. const text = "I am a developer"; console.log(text.indexOf("developer")); // prints 8 const text = "I am a developer, they call me a dev" console.log(text.lastIndexOf('dev')) // prints 33
replace(), replaceAll(), and search()
I added a search method to this list because there is a similar use case.
// the replace and replaceAll work exactly the same, // though the difference is that replaceAll() searches all occurences // and replaces them. const text = "Robert Green is one of the better authers" console.log(text.replace("better", "Best")); // prints Robert Green is one of the Best authors const texts = `His books focus on human nature and leadership. Unlike Robert T. Kiyosaki books which focus on finance and business`; console.log(texts.replaceAll("books", "podcasts")); // prints `His podcasts focus on human nature and leadership. //Unlike Robert T. Kiyosaki podcasts which focus on finance and business`; // Now let's look at the search method const searchText = `Books, blogs and podcasts are a great way to learn`; // The search method returns an index of the searched word or characters console.log(searchText.search("Books"))// prints 0; console.log(searchText.search(/Books/i)) // prints 0; // Note while looking at these methods. I urge you learn and look at // the time complexity of these methods.
slice(start, end) and substr(start, length)
Often you will need to separate some strings from other texts that you may have. The above methods will help you achieve that.
const sliceString = "Developers life" console.log(sliceString.slice(0,11));// prints Developers console.log(sliceString.substr(0, 3)) // prints Dev
includes()
Sometimes you have a string you want to cross-reference and see if it exists in the main text. That's where the includes comes in. It returns a boolean
const includeStr = "Lavender Haze by Taylor Swift" console.log(includeStr.includes("Swift"))// prints true console.log(includeStr.includes("Song")) // prints false
trim(), trimStart(), and trimEnd()
These methods remove spaces from a string
const trimText = " Developer life " console.log(trimText.trim())// prints "Developer life" console.log(trimText.trimStart()) // prints "Developer life " console.log(trimText.trimEnd()) // prints " Developer life"
toLowerCase() and toUpperCase(), toString(), and split()
These are some of the most common String methods. We will look at them one by one
const str = "I am a developer"; console.log(str.toLowerCase()) // prints "i am a developer" console.log(str.toUpperCase())// prints "I AM A DEVELOPER" console.log(str.split(" "))// prints ['I', 'am', 'a', 'developer'] const num = 12; console.log(num.toString()) // prints "12" // Note: as recall we looked at how to return ths back to a number // If you have not read that blog I will link it at the end of the one
The promise
In the previous article about Number data type, I promised to provide a solution to leetcode challenge called valid-number.
var isNumber = function(s) {
s = s.trim()
if(s === '') return false
else return s.indexOf('Infinity') === -1 && !isNaN(+s);
};
This Challenge is tagged Hard and yet if you look at the solution, It does not seem so. Which brings me to my point.
Think simple while tackling any programming challenges.
In this article, I will leave you with another challenge find-the-index-of-the-first-occurrence-in-a-string. Look through the methods we looked at today and solve this change. I will provide the solution in the next article. Look out.
Conclusion.
In this article, we looked at the Javascript String data type and its methods.
There is still a handful of other methods and use cases that we did not tackle.
However, it's a perfect way to move on and research more.
So if you found a challenge or you didn't get something clear, I will be happy to help.
Muhamad Rashid Mugaba
Happy coding.