-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregex_homework.js
78 lines (59 loc) · 2.03 KB
/
regex_homework.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Homework #2 - Regular Expressions with Iterators Lab / Homework
// ---------------------------------
var animalArray = ["Cat", "Dog", "Polar Bear", "Grizzly Bear", "Antelope", "Kangaroo", "Bear"];
// Object constructors
function Animals(animalArray) {
this.animal = animalArray;
};
// Using .filter()
// Return an array with only animals that have three-letter names.
Animals.prototype.threeLetterAnimal = function() {
return this.animal.filter(function(animal) {
return animal.length === 3;
});
};
// // Answer
// var threeLetterPattern = /^[A-z]{3}$/i;
// var threeLetterAnimals = animals.filter(function(element){
// return threeLetterPattern.test(element); //true
// });
// Return an array with only animals that have two-word names.
Animals.prototype.twoWordAnimal = function() {
return this.animal.filter(function(animal) {
var pattern = /[A-z]+ [A-z]+/ig;
return pattern.exec(animal);
});
};
// Return an array with only animals that don't start with the letter K.
Animals.prototype.charNotK = function() {
return this.animal.filter(function(animal) {
var pattern = /^[^k]/i;
return pattern.exec(animal);
});
};
// Using .map()
// Return an array that changes all animal names containing "bear" to "Teddy Bear".
Animals.prototype.beartoTeddy = function() {
return this.animal.map(function(animal) {
return animal.replace(/bear/ig, "Teddy Bear");
})
};
// Write a regular expression that checks if the animal is either cat or dog. If it is cat, replace the value with "Kitty Cat" and if it is a dog replace the value with "Puppy".
Animals.prototype.rename = function(animal) {
var patternCat = /^cat$/i;
var patternDog = /^dog$/i;
if(patternCat.test(element)) {
return "Kitty Cat";
} else if (patternDog.test(element)) {
return "Puppy";
} else {
return element;
}
};
var Animals = new Animals(animalArray);
// Log the results
console.log(Animals.threeLetterAnimal());
console.log(Animals.twoWordAnimal());
console.log(Animals.charNotK());
console.log(Animals.beartoTeddy());
console.log(Animals.rename());