create account

A deeper understanding of Strings on JavaScript by anomadsoul

View this thread on: hive.blogpeakd.comecency.com
· @anomadsoul · (edited)
$40.42
A deeper understanding of Strings on JavaScript
If you don't know what a string is, I highly recommend that you check out my previous posts about JavaScript, it will help you out to understand what the hell is happening here.

![image.png](https://images.ecency.com/DQmfTsHPfEi87kL9FoJKECq4GXnYAebJyZHffBeAcUHEBNp/image.png)
<center><sub>[Image source](https://javascript.plainenglish.io/useful-javascript-string-methods-dd336df89864)</sub></center>


Since a string is one of the most (if not the most) basic concept on JS, I will jump directly into examples and the most useful methods we can use on strings:

````
const hive = "Dapp Ecosystem";
const stableCoin = "HBD";

console.log(hive[1]); // *
````
<sub>Output: a
*We are calling the position zero of the string.
</sub>
***

We can also use a method to call the length of a string:
````
console.log(hive.length); // Output: 14
````
***
There are many methods that we can use with strings, one of them is to get the position in which a letter is in a string:
````
console.log(hive.indexOf("y"));
````
This only gives us the first occurrence, meaning that if there's the same letter twice in a string, it will return the first one.

To get the last occurrence of a letter in a string:
````
console.log(hive.lastIndexOf("s")); // 10
````

To search for entire words in a string, which is case sensitive:
```
console.log(hive.indexOf("Ecosystem")); // Output: 5 // *
````
<sub>*Which is the index where the word begins</sub>
***
Indexes are useful to extract parts of a string using the *.slice* method. This method needs indexes as arguments to work, so it is useful to know the indexes before extracting parts of a string.
````
console.log(hive.slice(5)); // Ecosytem *
````
<sub>*This is called a sub-string, it is just a part of the original string. This doesn't change the original string, it's almost impossible to mutate strings.
Inside the parentheses is the *begin* parameter
</sub>
***

To use the new substring we have to store it in a variable or data structure
````
const substring = hive.slice(5);
console.log(substring); // Ecosystem
````
There is also an end parameter for the *.slice* method. The second parameter established in which index of the string the slice should stop, and the index number is not included. If the end parameter is 5, the slice will stop at the fifth index, but will not include the 5th index in the new string.
````
console.log(hive.slice(5, 8)); // Eco
````
Until now we have just harcoded these values (input them manually), but sometimes we don't know the string that we will receive, so we have to adapt the code so it can work with any input we get. To extract the first word of any string, we can as follows:

We want the first word of the string, so we can hardcode the starting index, but we don't know how long the word is so, we use the *.indexof* method to find out where the first space is, and we establish that as the second parameter.
````
console.log(hive.slice(0, hive.indexOf(" "))); // Dapp
````

To return the last word it's the same logic as above but with a different method.

If we don't specify the end parameter, the slice will continue until the end.
````
console.log(hive.slice(hive.lastIndexOf(" "))); // " Ecosystem"
````

As you can see, this line of code returns the new string including the first space, we need to fix that by:
````
console.log(hive.slice(hive.lastIndexOf(" ") + 1)); // "Ecosystem"
````
There are many more use cases for the *.slice* method, like slicing the string in different positions, for example, from the end.
````
console.log(hive.slice(-7)); // osystem
````
We can specify a negative as an end parameter.
````
console.log(hive.slice(3, -3)); // p Ecosys
````
Now that we know the basics, we can begin to use these string methods and write functions.

For the next examples, consider that in a plane, the seats B and E are middle seats.
````
const checkMiddleSeat = function (seat) {
  const s = seat.slice(-1);
  if (s === "B" || s === "E") console.log(`You got a middle seat, too bad!`);
  else console.log(`You are safe from a middle seat!`);
};
checkMiddleSeat("23B"); // This modifies the variable
checkMiddleSeat("17A");
checkMiddleSeat("7E");
````

Some theory: Methods are only available in objects not on strings, so why does this work? Whenever we call a method on a string, JS converts that string primitive into a string object with the same content, and then on that created object interacts with the methods, this process is called boxing. When the method is finished, the object is then converted into a string primitive again by JS.

There are several more string methods in JS, and it would be kind of impossible for me and too boring for you to go through all of them, but I can go over the most used ones.

Changing the case on a string, which doesn't require any arguments:
````
const myself = "Eric AKA anomadsoul";
console.log(myself.toLowerCase()); // eric aka anomadsoul
console.log(myself.toUpperCase()); // ERIC AKA ANOMADSOUL
````
Fix capitalization in a word
````
const randomDude = "mIchael"; // Should be 'Michael'
const randomDudeLower = randomDude.toLowerCase(); // This converts everything to lower case.
// We take the first letter and convert it to upper case
const randomDudeCorrect =
  randomDudeLower[0].toUpperCase() + randomDudeLower.slice(1);
console.log(randomDudeCorrect); // Michael
````
There is a way we can do a function to do the same as we did here, but we are doing string methods here, not function, please focus.

Comparing strings:
````
const string1 = "anomadsoul@hive.io";
const string2 = " Anomadsoul@hive.Io ";
````
The second email should be correct as the user wrote it incorrectly but preserving the essence, so it is our job to make sure the second is valid when they log in.
````
const lowerString2 = string2.toLowerCase(); // First we convert it to lowercase
const trimmedString2 = lowerString2.trim(); // We are getting rid of the white spaces and enters.

console.log(trimmedString2); // anomadsoul@hive.io <- The correct one!
````
But we can do this all in one line of code, like this:
````
correctString2 = string2.toLowerCase().trim(); // Voila!

console.log(string1 === correctString2); // We compare them to check if indeed the second one is correctly written.
// Ouput: true
````
To replace parts of a string is one of the most important parts, so let's get into it.
````
const priceGB = "288,97£";
const priceUS = priceGB.replace("£", "$"); //
````
*The first argument is the one we want to replace, the second argument is the string that we want to replace it with.

Now we also would need to change the comma for a dot, but we can do it in one line of code by chaining.
````
const priceUS = priceGB.replace("£", "$").replace(",", ".");

console.log(priceUS); // 288.97$
````

The .replace method creates a new string, it doesn't mutate the old string.
````
const hello = "Hello Eric. It is great to meet Eric";
const helloJohn = hello.replaceAll("Eric", "John");
````

The replaceAll is not a method yet, but I have a good source saying it will be in the future, in the meantime, we can replace a word all over the string by:
````
console.log(hello.replace(/Eric/g, "John")); // Output: Hello John. It is great to meet John
````
We can also use methods on strings that return Booleans: .includes, .startswith and .endswith
````
const username = "@Pharesim";
console.log(username.includes("are")); // true
console.log(username.startsWith("P")); // false
console.log(username.endsWith("M")); // false
````
As you can see these methods are case sensitive.

Let's check if the string is a username
````
if (username.includes("@")) {
  console.log("This is a Hive username");
}
````
One of the most powerful string methods is split, which allows us to split a string into multiple strings by using a divider.
````
console.log("a-string-example".split("-")); // The argument we pass in is the divider. The method will split up the string using the '-' and will return the strings into elements of an array.
// Output: [ 'a', 'string', 'example' ]
// We can also use *space* as a divider.
console.log("Eric Anomadsoul".split(" "));
````
Then we can destructure the array directly in the code to have new variables.
````
const [firstName, userName] = "Eric Anomadsoul".split(" ");
console.log(firstName, userName);
````

The opposite of .split is .join and let's say I want to add an @ to the username and also convert the username into lowercase because that's how we should write usernames.
````
correctUsername = ["@", userName.toLowerCase()].join("");
console.log(correctUsername); // @anomadsoul
````
We already know how to convert the case of the strings and how to capitalize strings, but how would we deal with having to capitalize several words on a string?
````
const capitalizeName = function (name) {
  // 1
  const names = name.split(" ");
  const namesUpper = [];

  for (const word of names) {
    namesUpper.push(word[0].toUpperCase() + word.slice(1)); // 2
  }
  console.log(namesUpper.join(" ")); // 
};
capitalizeName("john smith smithson"); // John Smith Smithson
````
<sub>1.What we need to do is simple: Transform the first letter of each word into a capital letter, so to do that it is easier if we have an array of strings so we can loop over that array of strings.
2.We should store these new words into a new array, which is why we created the variable namesUpper
3.We then join the strings of the new array into a string.</sub>
***
There's another way of doing this, but I'm just showing it for the sake of having different ways:
````
const capitalizeName2 = function (name2) {
  // 1
  const names2 = name2.split(" ");
  const namesUpper2 = [];

  for (const word of names2) {
    namesUpper2.push(word.replace(word[0], word[0].toUpperCase()));
  }
  console.log(namesUpper2.join(" ")); // 2
};
capitalizeName2("smith john johnson"); // Smith John Johnson
````
<sub>1.What we need to do is simple: Transform the first letter of each word into a capital letter, so to do that it is easier if we have an array of strings so we can loop over that array of strings.
2.We then join the strings of the new array into a string.
</sub>
***
Padding a string means to add a number of characters to the string, until the string has a certain desired length.
````
const message = "This string is shy of fifty characters long!";

console.log(message.padStart(50, "_")); // 1
// Output: ______This string is shy of fifty characters long!

console.log(message.padEnd(50, "+"));
// This string is shy of fifty characters long!++++++
````
<sub>1.padStart will add characters to the beginning of the string. The first argument is the desired length after the padding. The second argument is the character we want to pad the string with.</sub>
***

A real life example for some these methods is when we type in a credit card number, and we never see the whole card, just the last four numbers, right? Let's how that is accomplished, We must take the last 4 numbers and then create a padstart to replace the first 12 numbers with a symbol.
````
const hideCreditCard = function (number) {
  // const str = String() // 1
  const str = number + ""; // 2
  const last = str.slice(-4);
  return last.padStart(str.length, "x");
};

console.log(hideCreditCard(4661654712348954));
hideCreditCard("1234567898745632");
````
<sub>1.First we convert the number into a string, we can do it like this or like below:
2.This works because if we add a string and a number, JS converts the result into a string.</sub>

To finish, the last method that is worth learning for strings is .repeat (not that the others I didn't mention are not worth it, but we are not prepared to go into the rabbit hole of strings yet, besides with this we already learned is enough to get by)
````
const letsRepeat = "This will be repeated... And once more...";
console.log(letsRepeat.repeat(3)); // 1

// Output: This will be repeated... And once more...This will be repeated... And once more...This will be repeated... And once more...

````
<sub>As you can imagine, the argument is the number of times we want to repeat the string.</sub>

***
***
***

That's it for strings, if you made it this far you are more than ready to take on strings by yourself, manipulate them and maybe even come up with chain of methods that will help you accomplish what you want with your strings in your code.

I hope this was helpful!
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 209 others
properties (23)
authoranomadsoul
permlinka-deeper-understanding-of-string
categoryhive-169321
json_metadata{"links":["https://javascript.plainenglish.io/useful-javascript-string-methods-dd336df89864"],"image":["https://images.ecency.com/DQmfTsHPfEi87kL9FoJKECq4GXnYAebJyZHffBeAcUHEBNp/image.png"],"users":["anomadsoul"],"tags":["hive-169321"],"app":"ecency/3.0.19-vision","format":"markdown+html"}
created2021-11-09 04:30:36
last_update2021-11-09 04:31:09
depth0
children0
last_payout2021-11-16 04:30:36
cashout_time1969-12-31 23:59:59
total_payout_value20.263 HBD
curator_payout_value20.152 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length12,363
author_reputation1,624,744,888,546,638
root_title"A deeper understanding of Strings on JavaScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id107,613,955
net_rshares35,541,180,710,334
author_curate_reward""
vote details (273)