Exercise Solutions: Strings¶
Part One¶
The
lengthmethod returns how many characters are in a string. However, the method will NOT give us the length of a number. Ifnum = 1001,num.lengthreturnsundefinedrather than 4.
Use type conversion to print the length (number of digits) of an integer.
let num = 1001;
What if
numcould be EITHER an integer or a decimal? Add anif/elsestatement so your code can handle both cases. (Hint: Consider theindexOf()orincludes()string methods).
1 2 3 4 5 | if (String(num).includes('.')){
console.log(String(num).length-1);
} else {
console.log(String(num).length);
}
|
Part Two¶
Remember, strings are immutable. Consider a string that represents a strand of DNA:
dna = " TCG-TAC-gaC-TAC-CGT-CAG-ACT-TAa-CcA-GTC-cAt-AGA-GCT ". There are some typos in the string that we would like to fix:
Use the
trim()method to remove the leading and trailing whitespace, and then print the results.
1 2 3 | let dna = " TCG-TAC-gaC-TAC-CGT-CAG-ACT-TAa-CcA-GTC-cAt-AGA-GCT ";
let newString = dna.trim();
console.log(newString);
|
Note that if you try
console.log(dna)after applying the methods, the original, flawed string is displayed. To fix this, you need to reassign the changes back todna. Apply these fixes to your code so thatconsole.log(dna)prints the DNA strand in UPPERCASE with no whitespace.
1 2 3 | let dna = " TCG-TAC-gaC-TAC-CGT-CAG-ACT-TAa-CcA-GTC-cAt-AGA-GCT ";
dna = dna.trim().toUpperCase();
console.log(dna);
|
Let's use string methods to do more work on the DNA strand:
Replace the sequence
'GCT'with'AGG', and then print the altered Sstrand.
1 2 | dna = dna.replace('GCT','AGG');
console.log(dna);
|
Use
slice()to print out the fifth set of 3 characters (called a codon) from the DNA strand.
console.log(dna.slice(16,19));
Just for fun, apply methods to
dnaand use another template literal to print,'taco cat'.
console.log(`${dna.slice(4,7).toLowerCase()}o ${dna.slice(dna.indexOf('CAT'),dna.indexOf('CAT')+3).toLowerCase()}`);
Part Three¶
If we want to turn the string
'JavaScript'into'JS', we might try.remove(). Unfortunately, there is no such method in JavaScript. However, we can use our cleverness to achieve the same result.
Use string concatenation and two
slice()methods to print'JS'from'JavaScript'.
1 2 | let language = 'JavaScript';
console.log(language.slice(0,1)+language.slice(4,5));
|
Use bracket notation and a template literal to print,
"The abbreviation for 'JavaScript' is 'JS'."
console.log(`The abbreviation for '${language}' is '${initials}'.`)
