Skip to content

Commit ca575de

Browse files
committed
complete working with strings
1 parent eba5271 commit ca575de

File tree

4 files changed

+404
-6
lines changed

4 files changed

+404
-6
lines changed

09-Data-Structure-Modern-Operators-and-Strings/README.md

+247-5
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ We an also use the `rest` on `DOM` elements, which allows us to do advanced func
482482
rest.get(document.querySelector("h1"));
483483
```
484484
485-
### Maps Iteration
485+
# Maps Iteration
486486
487487
Elements are added to a `Map` using the `set()` method. But this can be cumbersome if you're trying to add multiple elements at the same time. To fix that, we can create a new `map` using an array inside the `map`.
488488
@@ -579,7 +579,7 @@ Now there are other data structures not built into JavaScript like:
579579
580580
## Arrays vs Sets & Objects vs Maps
581581
582-
## Arrays
582+
### Arrays
583583
584584
```js
585585
const tasks = ["Code", "Eat", "Code"];
@@ -589,7 +589,7 @@ const tasks = ["Code", "Eat", "Code"];
589589
1. Use arrays when you need **ordered** list of values(with duplicates).
590590
2. Use arrays when you need to **manipulate** data
591591
592-
## Sets
592+
### Sets
593593
594594
```js
595595
const task = new Set(["Code", "Eat", "Code"]);
@@ -600,7 +600,7 @@ const task = new Set(["Code", "Eat", "Code"]);
600600
2. Use Sets when **high performance** is really important.
601601
3. Use Sets to **remove duplicates** from arrays.
602602
603-
## Objects
603+
### Objects
604604
605605
```js
606606
const task = {
@@ -615,7 +615,7 @@ const task = {
615615
3. Use when you need to include `functions` (methods)
616616
4. Use when working with `JSON` (can covert to `Map`)
617617
618-
## Maps
618+
### Maps
619619
620620
```js
621621
const task = new Map([
@@ -631,3 +631,245 @@ const task = new Map([
631631
4. Easy to compute size
632632
5. Use when you simply need to map key to values
633633
6. Use when you need keys that are not strings.
634+
635+
# Working with Strings - Part 1
636+
637+
In JavaScript we work a lot with strings and there are some important `string methods` worth knowing. This methods are very similar with the `array methods`
638+
639+
We can get elements in a string using the dot notation and the postion number. (Like arrays, strings are also zero-based)
640+
641+
```js
642+
const airline = "Dana Air Nigeria";
643+
const plane = "Boeing 700";
644+
645+
console.log(plane[0]); // output B
646+
console.log(plane[1]); // output o
647+
console.log(plane[2]); // output e
648+
console.log("B737"[0]); // output B
649+
```
650+
651+
We can also get the lenght of a string and the position of an element in a string.
652+
653+
```js
654+
console.log(airline.length); // output 16
655+
console.log("B737".length); // output 4
656+
657+
console.log(airline.indexOf("a")); // output 1
658+
console.log(airline.lastIndexOf("a")); // output 15
659+
console.log(airline.indexOf("Codo")); // output -1 (since result is not found)
660+
```
661+
662+
### Slice Method
663+
664+
The `slice()` method returns a shallow copy of a portion of an arrayl or string into a new array object selected from `start` to `end`
665+
666+
Syntax
667+
668+
```js
669+
slice();
670+
slice(start);
671+
slice(start, end);
672+
```
673+
674+
The importance of using these indexes is using the `slice()` method to get `indexOf` of a string element or array.
675+
676+
**Start**
677+
678+
```js
679+
console.log(airplane.slice(5));
680+
```
681+
682+
This will slice the string `Dana Air Nigeria` by five positions and output the remaining result, which will be `Air Nigeria`
683+
684+
The result of a sliced string is referred to as a **sub string** because it does not change the original string. Of course this is because strings are immutable.
685+
686+
If you need to change the string, you would have to store it in a variable or data structure.
687+
688+
**End**
689+
690+
```js
691+
console.log(airplane.slice(4, 7));
692+
```
693+
694+
The result will be `Ai` because 4 will slice `Dana ` and 7 will slice `r Nigeria`
695+
696+
> **Note**
697+
> The lenght of the extracted string(sub string) will always be `start - end`. In the example above `7 - 4 = 2` hence the result(Ai)
698+
699+
In real world example, we may not know the string we wish to extract. So how do you extract a string if we didn't know what it is? We use the `indexOf()` method.
700+
701+
```js
702+
console.log(airline.slice(0, airline.indexOf(" ")));
703+
```
704+
705+
Here we're starting from 0 and slicing the first occurence of the space`(' ')`, which will give us `Dana`
706+
707+
And if we want to start from the last item:
708+
709+
```js
710+
console.log(airline.slice(0, airline.lastIndexOf(" ")));
711+
```
712+
713+
We can also use negative values:
714+
715+
```js
716+
console.log(airline.slice(-2)); // ia
717+
console.log(airline.slice(-6)); // igeria
718+
console.log(airline.slice(-11)); // Air Nigeria
719+
console.log(airline.slice(1, -11)); // ana
720+
```
721+
722+
Let's practice what we just learned by writing a function that recieves an airplane sit and logs to the console if it is a middle sit or not.
723+
724+
Note that there are 6 sits in a row from `A - F`
725+
726+
```js
727+
const checkMiddleSeat = function (seat) {
728+
// B & E are middle seats
729+
const x = seat.slice(-1);
730+
if (x === "B" || x === "E") {
731+
console.log(`${x} is a middle seat`);
732+
} else {
733+
console.log(`${x} is not a middle seat`);
734+
}
735+
};
736+
737+
checkMiddleSeat("11B");
738+
checkMiddleSeat("23C");
739+
checkMiddleSeat("3E");
740+
```
741+
742+
The result will be:
743+
744+
- B is a middle seat
745+
- C is not a middle seat
746+
- E is a middle seat
747+
748+
# Working with Strings - Part 2
749+
750+
### Capitalization `(toLowerCase() & toUpperCase())`
751+
752+
```js
753+
const passenger = "vICtOR";
754+
const passengerLower = passenger.toLowerCase();
755+
const passengerCorrect =
756+
passengerLower[0].toUpperCase() + passengerLower.slice(1);
757+
console.log(passengerCorrect);
758+
759+
// Function
760+
const correctName = function (name) {
761+
const low = name.toLowerCase();
762+
const correct = low[0].toUpperCase() + low.slice(1);
763+
return correct;
764+
};
765+
766+
console.log(correctName("jOHn"));
767+
```
768+
769+
### Comparing strings
770+
771+
```js
772+
const email = "hello@eke.io";
773+
const loginEmail = " Hello@eKE.Io \n";
774+
775+
const lowerEmail = loginEmail.toLowerCase();
776+
const trimmedEmail = lowerEmail.trim();
777+
console.log(trimmedEmail);
778+
```
779+
780+
Similar to the `Map` `set()` method, we can join string methods together.
781+
782+
```js
783+
const normalEmail = loginEmail.toLowerCase().trim();
784+
console.log(normalEmail); // output hello@eke.io
785+
console.log(email === normalEmail); // output true
786+
```
787+
788+
### Replacing
789+
790+
Let's try replacing a currency type and the trailing period with a comma
791+
792+
```js
793+
const priceNG = "₦288.97";
794+
console.log(priceNG);
795+
const priceGB = priceNG.replace("", "£").replace(".", ",");
796+
console.log(priceGB);
797+
```
798+
799+
Replace words.
800+
801+
```js
802+
console.log(announcement.replace("door", "gate")); // Replace first occurence of the word 'door'
803+
console.log(announcement.replaceAll("door", "gate")); // Replace all occurence
804+
```
805+
806+
Another way we can do this is by using a regular expression.
807+
808+
```js
809+
console.log(announcement.replace(/door/g, "gate"));
810+
```
811+
812+
Just like all of the previous methods, the replace method is also case sensitive.
813+
814+
### Booleans
815+
816+
There are three methods that returns a boolean (`includes()`, `startsWith()`, `endsWith()`)
817+
818+
```js
819+
const planes = "Airbus A320neo";
820+
console.log(planes.includes("A320")); // true
821+
console.log(planes.includes("Boeing")); // false
822+
console.log(planes.startsWith("Air")); // false
823+
824+
if (planes.startsWith("Airbus") && planes.endsWith("neo")) {
825+
console.log("Part of the New Airbus family");
826+
}
827+
```
828+
829+
#### Practice Exercise
830+
831+
```js
832+
const checkBaggage = function (items) {
833+
const baggage = items.toLowerCase();
834+
if (baggage.includes("knife") || baggage.includes("gun")) {
835+
console.log("You are NOT allowed on board");
836+
} else {
837+
console.log("Welcome aboard");
838+
}
839+
};
840+
841+
checkBaggage("I have a laptop, some Food and a pocket Knife");
842+
checkBaggage("Socks and camera");
843+
checkBaggage("Get some snacks and a gun for protection");
844+
```
845+
846+
### Capitalize Name
847+
848+
```js
849+
const capitalizeName = function (name) {
850+
const names = name.split(" ");
851+
const namesUpper = [];
852+
853+
for (const n of names) {
854+
// namesUpper.push(n[0].toUpperCase() + n.slice(1));
855+
// Using replace
856+
namesUpper.push(n.replace(n[0], n[0].toUpperCase()));
857+
}
858+
console.log(namesUpper.join(" "));
859+
};
860+
```
861+
862+
## Summary
863+
864+
- `toLowerCase()`: Converts all the alphabetic characters in a string to lowercase.
865+
- `toUpperCase()`: Converts all the alphabetic characters in a string to uppercase.
866+
- `trim()`: Removes the leading and trailing white space and line terminator characters from a string
867+
- `replace()`: Replaces text in a string, using a regular expression or search string.
868+
- `replaceAll()`: Replaces all occurence of text in a string, using a regular expression or search string.
869+
- `indexOf()`: Returns the position of the first occurrence of a substring.
870+
- `lastIndexOf()`: Returns the last occurrence of a substring in the string.
871+
- `slice()`: Returns a section or the index to the beginning of the specified portion of stringObj
872+
- `starsWith()`: Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.
873+
- `endsWith()`: Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at endPosition – length(this). Otherwise returns false.
874+
- `padStart`: Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. The padding is applied from the start (left) of the current string.
875+
- `padEnd`: Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string.

0 commit comments

Comments
 (0)