-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
70 lines (62 loc) · 1.91 KB
/
script.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
function getName() {
const url = document.URL;
const indexOfPeriod = url.indexOf(".");
let name = url.substring(8, indexOfPeriod);
return firstLetterToUpperCase(name);
}
async function fetchJoke() {
const url = "https://api.chucknorris.io/jokes/random";
const response = await fetch(url);
const json = await response.json();
return json.value;
}
function getJokeWithNewName(name, joke) {
joke = replaceAllOccurances(joke, "Chuck Norris", name);
joke = replaceAllOccurances(joke, "Chuck", name);
joke = replaceAllOccurances(joke, `${name}'`, `${name}'s`);
return joke;
}
function getJokeWithNewGender(joke) {
joke = replaceAllOccurances(joke, "he", "she");
joke = replaceAllOccurances(joke, "He", "She");
joke = replaceAllOccurances(joke, "him", "her");
joke = replaceAllOccurances(joke, "Him", "Her");
joke = replaceAllOccurances(joke, "his", "her");
joke = replaceAllOccurances(joke, "His", "Her");
return joke;
}
function replaceAllOccurances(joke, toBeReplaced, replaceWith) {
const regex = new RegExp("\\b" + toBeReplaced + "\\b");
let index = joke.search(regex);
console.log(joke);
while (index >= 0) {
joke = joke.replace(regex, replaceWith);
index = joke.search(regex);
}
return joke;
}
async function setJoke(name) {
const joke = await fetchJoke();
let fixedJoke = getJokeWithNewName(name, joke);
if (name === "Ninafina") {
fixedJoke = getJokeWithNewGender(fixedJoke);
}
const element = document.getElementById("joke");
element.innerText = firstLetterToUpperCase(fixedJoke);
}
async function setButton(name) {
const button = document.getElementById("button");
console.log(button);
button.addEventListener("click", () => {
setJoke(name);
});
}
function firstLetterToUpperCase(str) {
return str[0].toUpperCase() + str.slice(1);
}
const name = getName();
document.title = `Ka faen ${name}?`;
setJoke(name);
window.onload = () => {
setButton(name);
};