30 Days Of JavaScript.2E
Day 2. Data Types_Exercise
On
day 2
, I learned about primitive and non-primitive(reference) data types, mostly numbers and strings. Day 2 features bunch of math objects and string methods, along with casting(converting data types.)
I suffered with exercises on this lesson because figuring out where and how to use all those string methods was a lot to take for me. But practice makes improvement! Let’s dive in!
👟Level 2.
4) Check if parseFloat(‘9.8’) is equal to 10 if not make it exactly equal with 10.
console.log(parsefloat('9.8')) == 10); //false
console.log(Math.ceil(parseFloat('9.8')) == 10); //true
5) Check if ‘on’ is found in both python and jargon.
let str1 = 'python';
let str2 = 'jargon';
console.log(str1.includes('on')); //true
console.log(str2.includes('on')); //true
To find if certain string is found in a text, use
includes()
!
7) Generate a random number between 0 and 100 inclusively.
console.log(Math.floor(Math.random() * 101));
I learned how to generate random number between 0 and 10. Math.random()
would generate random number between 0-0.999. I multiplied 11 so that the range would become 0-10.99.
I first thought I should multiply 110(for no reason) but the number 11 was actually made from (10+1). So if I want to make the biggest number slightly over 100, I should multiply (100+1)=101.
8) Generate a random number between 50 and 100 inclusively.
console.log((Math.floor(Math.random() * 51))+50);
In this case, the starting point isn’t 0, so I considered the range first. So I have to make out 0-50 out of 0-0.999. Then I’ll add 50 to the range. Again, the number I have to multiply would be 51(=50+1). The range of 0~50.999 will come out, and Math.floor
method will make it to 0-50. Adding 50 to the range, I can get random number between 50-100 inclusively.
10) Access the ‘JavaScript’ string characters using a random number.
let string = 'JavaScript';
let random = string[Math.floor(Math.random() * 11))];
console.log(random);
let string = 'JavaScript';
console.log(string.charAt(Math.floor(Math.random() * 11)));
Looking back, it wasn’t that hard, but I had a hard time understanding the problem itself. First I thought the question wanted me to access to string characters(like a-z, A-Z) in JavaScript.(I didn’t notice single quotes…) So I googled it, and some weird functions that I’ve never seen came out, regarding regEx and so…
Then I looked over my notebook, and found string method number 2 ‘accessing characters in a string - using its index’. That was a clue, and the first answer came out. Before finding this out, I thought I could use a charAt()
method and I came up with the second answer. But I think the first one using string index([ ]) might be a proper answer.
11) Use console.log() and escape characters to print the following pattern.
1 1 1 1 1
2 1 2 4 8
3 1 3 9 27
4 1 4 16 64
5 1 5 25 125
I suffered with this one too, with the same reason above - I overthought it. I realized that thinking outside of the question doesn’t really helps. I’m in the beginner’s level, and I really don’t know how to do fancy stuffs like using functions or conditions.
The first thing that caught my brain was that those numbers have some common rules(a ** 1 a ** 0 a ** 1 a ** 2 a ** 3). And I thought I could write a single line of code, set those ‘a’s(1, 2, 3, 4, 5) as array and so… But again that was way above me. The question only asked for using console.log()
and escape characters
. What I just had to do is below.
console.log
('1 1 1 1 1\n2 1 2 4 8\n3 1 3 9 27\n4 1 4 16 64\n5 1 5 25 125);
One thing to notice is that the
\n
itself just funcions as anEnter Key
. So if I hit space key after it, the next line will start with a space.
👟Level 3.
1) ‘Love is the best thing in this world. Some found their love and some are still looking for their love.’ Count the number of word love in this sentence.
let string = 'Love is the best thing in this world. Some found their love and some are still looking for their love.';
let pattern = /love/gi;
console.log(string.match(pattern));
If I use match()
method, and use regular expressions, I can get an array of the matching string I was looking for. If I use console.log(string.match('love'));
, it would just give me an array that doesn’t tell the count. It’s because I didn’t set g
after it. match('love')
will only find the first match.
3-1) Clean the following text. (hint, use replace and regular expressions).
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching';
To ‘clean’ the text, I have to remove all the special characters including %, $, @, #, &. In other words, the remaining texts should be all English or numbers. I think I should extract those special symbols with regular expressions, and then replace those with ‘‘(empty space).
- Here’s my first approach(before googling):
let regEx = /%, $, @, #, &/g;
console.log(sentence.replace(regEx, ''));
It didn’t work. I guess /%, $, @, #, &/g
finds ‘%, $, @, #, &’ as a set. I didn’t know what to do, so I googled it. First I found this article about removing special characters. Then I found the site about regular expressions regarding special characters. I thought I could use \w
or \W
.
- I used
\W
first.
let pattern = sentence.replace(/\W/g, '');
- and… it turned out like this.
IamateacherandIloveteachingThereisnothingasmorerewardingaseducatingandempoweringpeopleIfoundteachingmoreinterestingthananyotherjobsDoesthismotivateyoutobeateacherThis30DaysOfJavaScriptisalsotheresultofloveofteaching
I guess \W
wipes out the blank space too, since a black space isn’t a word character. So finally I used \w
. \w
‘matches any alphanumeric character from the basic Latin alphabet, including the underscore,’ so I had to reverse the meaning.
let pattern = sentence.replace(/[^\w ]/g, '');
console.log(pattern);
The caret(^) symbol means “not the following characters”, and I should use global flag(g) to search all of the charcters in a string. To leave the space in the sentence, I had to put an empty space after w. It would mean, ‘replace what is not a word character and a space, to nothing.’
- The result:
I am a teacher and I love teaching There is nothing as more rewarding as educating and empowering people I found teaching more interesting than any other jobs Does this motivate you to be a teacher This 30DaysOfJavaScript is also the result of love of teaching
The fact that all the dots and question marks are all gone irritated me… So I did another google search and find this article about Regex. It definitely helped me out the most, because I learned how to select multiple values in Regex - by using OR operator(|).
- So my following approach was:
let pattern = sentence.replace(/@|#|;|!|%|&|$/g, '');
console.log(pattern);
It all worked out except for the dollar sign. So I tried putting single or double quotes on $
, but the result was the same. I googled it again, and I finally got the answer on stackoverflow. The dollar sign turned out to have special meaning on regex.
To assign a dollar sign(
$
) as a string value on Regular expressions, I should use\$
or\\$
.
- Final approach (answer):
let pattern = sentence.replace(/@|#|;|!|%|&|\$/g, '');
console.log(pattern);
//I am a teacher, and I love teaching. There is nothing as more rewarding as educating and empowering people. I found teaching more interesting than any other jobs. Does this motivate you to be a teacher? This 30DaysOfJavaScript is also the result of love of teaching
3-2) Find the most frequent word.(hint, use replace and regular expressions).
I can split the string by empty spaces using split()
, so that I can get an array of words in the string. Before that, I removed special characters from the sentence first.
let pattern = sentence.replace(/[^\w ]/g, '');
console.log(pattern.split(' '));
let words = sentence.match(/\w+/g);
console.log(words);
//(46) ['I', 'am', 'a', 'teacher', 'and', 'I', 'love', 'teaching', 'There', 'is', 'nothing', 'as', 'more', 'rewarding', 'as', 'educating', 'and', 'empowering', 'people', 'I', 'found', 'teaching', 'more', 'interesting', 'than', 'any', 'other', 'jobs', 'Does', 'this', 'motivate', 'you', 'to', 'be', 'a', 'teacher', 'This', '30DaysOfJavaScript', 'is', 'also', 'the', 'result', 'of', 'love', 'of', 'teaching']
This way, I got the list of words in the sentence. Now what I have to do is to find the most frequent word from the list. I found out that match()
could also give me an array of words, without removing special characters.
I came back from day 7 to solve this.
I spent more than 4 hours getting to know how to solve this one. Here’s the lists of sites I looked up for.
-
stackoverflow: how to use a variable in a regular expression? - got the idea of using
RegExp
-
stackoverflow: how to count the occurrences of array elements - got the idea of checking if a value appears only once
//only one value in the array
if (arr.indexOf(value) == arr.lastIndexOf(value))
//more than one value in the array
if (arr.indexOf(value) != arr.lastIndexOf(value))
- stackoverflow: how to remove same elements in an array - got the idea of using
Set
.
uniq = [...new Set(array)];
The sequence of the process:
- remove all the punctuation and lowercase all the words(to make it easier to match) ->
wordsList
- split the sentence to make an array of words that compose the sentence ->
words
- remove the same elements from the array ->
uniqWords
- running through each elements(unique ones), match the element with the
wordsList
and store the length of an array.(match()
returns an array if there’s a match.)
const sentence = 'I am a teacher, and I love teaching. There is nothing as more rewarding as educating and empowering people. I found teaching more interesting than any other jobs. Does this motivate you to be a teacher? This 30DaysOfJavaScript is also the result of love of teaching';
let wordsList = sentence.replace(/\W+/g, ' ').toLowerCase();
let words = wordsList.split(' ');
let uniqWords = [...new Set(words)];
for (let i = 0; i < uniqWords.length; i++) {
let re = new RegExp( ` ${uniqWords[i]} `, 'g');
console.log(`${uniqWords[i]}: ${wordsList.match(re).length}`);
}
Here, to actually sort out the most frequently-used word, I used Math.max
to find the highest matching number. Then I printed out every word that has the same number(the highest number).
const sentence = 'I am a teacher, and I love teaching. There is nothing as more rewarding as educating and empowering people. I found teaching more interesting than any other jobs. Does this motivate you to be a teacher? This 30DaysOfJavaScript is also the result of love of teaching';
let wordsList = sentence.replace(/\W+/g, ' ').toLowerCase();
let words = wordsList.split(' ');
let uniqWords = [...new Set(words)];
const uniqWordsArr = [];
for (let i = 0; i < uniqWords.length; i++) {
let re = new RegExp( ` ${uniqWords[i]} `, 'g');
uniqWordsArr.push(wordsList.match(re).length);
let max = Math.max(...uniqWordsArr);
if (uniqWordsArr[i] == max) {
console.log(uniqWords[i]);
}
} //i, a, teacher, and, love, teaching, is, as, more, this, of
I’m back from Day 8. I found another article that would help - how to get all characters in a string in JavaScript. It’s slightly off from what I was doing above, but I think it’ll be useful.
4) Calculate the total annual income of the person by extracting the numbers from the following text. ‘He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.’
const text= 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.';
let numbers = text.match(/\d+/g);
console.log(numbers); //(3) ['5000', '10000', '15000']
console.log(5000 * 12 + 10000 + 15000 * 12); //250000
‘d’ with an escape character acts as a digit.
\d+
means one or more digit numbers. Theg
after is a global flag, to search everywhere in the given variable.
- Another idea from 30DaysOfJS chats:
const text= 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.';
let numbers = text.match(/\d+/g);
let totalAnnualIncome = parseInt(numbers[0] * 12) + parseInt(numbers[1]) + parseInt(numbers[2] * 12);
console.log(totalAnnualIncome); //250000
If there’s a match,
match()
returns an array. If I am to find the numbers in a string, the elements of the array would be a type of string. So, to calulate those as numbers, I should change the data type(casting).
Leave a comment