const doubleQuoteStr = "JavaScript";
const singleQuoteStr = 'JavaScript';
let count = 0
console.log('Current count is %s', count);
Template literals as opposed to substitions above are a better approach to using placeholders in a string.
Template literals are backtick embedded strings with the use of ${variableName}
as a placeholder.
const value1 = 10;
const value2 = 23;
console.log(`value 1 is ${value1} and value 2 is ${value2}, sum is ${value1 + value2}`);
// value 1 is 10 and value 2 is 23, sum is 33
let today = 'Friday';
let greeting = 'Thank God it\'s';
console.log(`${greeting} ${today}`);
const stringObjectInstance = new String('String Object instance.');
console.log(stringObjectInstance); // [String: 'String Object instance.']
const language = 'JavaScript';
console.log(`The length of ${language} is ${language.length}`); // The length of JavaScript is 10
const name = 'Alex';
const firstChar = name[0];
console.log(firstChar); // A
const name = 'Sarah';
const char = name.charAt(name.length - 1);
console.log(char); // h
if ('a' < 'b') {
console.log('a is less than b'); // a is less than b
}
if ('z' > 'Z') {
console.log('Z is greater than z'); // Z is greater than z
}
const stringObject = new String('Bob Marley');
console.log(stringObject); // [String: 'Bob Marley']
console.log(stringObject.valueOf()); // Bob Marley
console.log('10 + 5') // 10 + 5
console.log(eval('10 + 2')) // 12
const str1 = 'Learning';
const str2 = 'JavaScript';
console.log(str1 + ' ' + str2); // Learning JavaScript
Be careful with accidentally thinking the logic below will result in a math addition
const value1 = '1';
const value2 = 1;
// answer is 11 here as JavaScript will treat the evaluation as concatenation of two String not adding numbers e.g 1 + 1 is 2.
console.log(value1 + value2)
const firstName = 'John';
const lastName = 'Appleseed';
const formattedLastName = ` ${lastName}`
console.log(`The person\'s full name is ${firstName.concat(formattedLastName)}`); // The person's full name is John Appleseed
Some escape characters \', \" and \n
. See documentation for a list of more escape characters.
// \'
const escapeSingleQuote = 'Alex\'s Book';
console.log(escapeSingleQuote); // Alex's Book
// \"
const escapeDoubleQuote = 'Swift\"s latest version is 5.3';
console.log(escapeDoubleQuote); // Swift"s latest version is 5.3
// \n
const newLine = 'Today is Sunday.\nReturned from a weekend trip.';
console.log(newLine);
/*
Today is Sunday.
Returned from a weekend trip.
*/
const longLiteralString = "Welcome to JavaScript " +
"the language " +
"of the web."
console.log(longLiteralString);
let stringNum = '150';
console.log(parseInt(`${2020 + 1}`)); // 2021
console.log(parseInt(stringNum)); // 150
console.log(parseInt('eight')); // NaN
console.log(parseInt('0xF')); // hexadecimal number
console.log(parseInt(' 123')); // 123, ignores the spaces
console.log(parseInt('.123')); // NaN , sees a special character and return NaN (not a number)
console.log(parseInt('1 23')); // 1 , only parses the first number and ignores everything after the space
console.log(parseFloat(2.50 + 0.13)); // 2.63
console.log(parseFloat('five')); // NaN
let number = 150;
let floatValue = 1.50;
console.log(number.toString()); // '150'
console.log(floatValue.toString()); // '1.50'
console.log((100).toString()); // '100'
split
is used to separate a given string by a given character and form and array.
const str = 'Every developer should learn JavaScript.';
const spaceSeparated = str.split(' ');
console.log(spaceSeparated); // [ 'Every', 'developer', 'should', 'learn', 'JavaScript.' ]
const noCharSeparation = str.split('');
console.log(noCharSeparation);
/*
[
'E', 'v', 'e', 'r', 'y', ' ', 'd',
'e', 'v', 'e', 'l', 'o', 'p', 'e',
'r', ' ', 's', 'h', 'o', 'u', 'l',
'd', ' ', 'l', 'e', 'a', 'r', 'n',
' ', 'J', 'a', 'v', 'a', 'S', 'c',
'r', 'i', 'p', 't', '.'
]
*/
indexOf
is used to search the first occurrence of a substring.
const str = 'Prior to Swift, iOS developers used Objective-C to write apps.';
const searchWord = 'Objective-C';
const index = str.indexOf(searchWord);
console.log(`${searchWord} was found at index ${index}`); // Objective-C was found at index 36
includes()
returns a boolean value indicating the presence of a substring in a given string.
const str = 'Thanksgiving is one of the biggest holidays of the year';
const searchWord = 'Thanksgiving';
console.log(`\`${searchWord}\` ${str.includes(searchWord) ? `is` : `is not`} in the sentence.`);
// `Thanksgiving` is in the sentence.
Creates a substring
from given indices.
const language = 'JavaScript';
const substring = language.substring(0, 4);
console.log(substring); // Java
Replace the occurrence of a substring with another string.
let currentLanguage = 'I am currently learning Swift.';
currentLanguage = currentLanguage.replace('Swift', 'JavaScript');
console.log(currentLanguage); // I am currently learning JavaScript.
MDN documentation: The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
const str = 'JavaScript';
slicedStr = str.slice(0, 4);
console.log(slicedStr); // Java
let slicedStr = str.slice(-6);
console.log(slicedStr); // Script
Use escape characters to console log: We are "Vikings".
Solution
console.log('We are \"Vikings\"'); // We are "Vikings"
Create two constants to store "Hello" and "Swift" to form "Hello Swift".
Solution
const msg1 = 'Hello';
const msg2 = 'Swift';
console.log(msg1 + ' ' + msg2); // "Hello Swift"
Create a function called verbing
. It should take a single argument, a string.
If its length is at least 3, it should add 'ing' to its end, unless it already ends in 'ing', in which case it should add 'ly' instead.
If the string length is less than 3, it should leave it unchanged. For example:
verbing('swim'): 'swimming'
verbing('swimming'): 'swimmingly'
verbing('go'): 'go'
Solution
function verbing(inputString) {
if (typeof inputString !== 'string') {
console.log('Not a valid string.');
return;
}
if (inputString.length >= 3) {
const lastCharIndex = inputString.length;
const suffix = inputString.substring(lastCharIndex - 3, lastCharIndex);
if (suffix === 'ing') {
inputString += 'ly'
} else {
inputString += 'ing';
}
}
return inputString;
}
console.log(verbing('swim')); // swiming
console.log(verbing('swimming')); // swimmingly
console.log(verbing('go')); // go
Create a function called mixUp
. It should take in two strings, and return the concatenation of the two strings (separated by a space) slicing out and swapping the first 2 characters of each. You can assume that the strings are at least 2 characters long. For example:
mixUp('mix', pod'); // 'pox mid'
mixUp('dog', 'dinner'); // 'dig donner'
Look up the JavaScript string reference to find methods which may be useful!
Solution
function mixUp(str1, str2) {
const str1Prefix = str1.substring(0, 2);
const str2Prefix = str2.substring(0, 2);
str1 = str1.replace(str1Prefix, str2Prefix);
str2 = str2.replace(str2Prefix, str1Prefix);
return str1.concat(` ${str2}`);
}
console.log(mixUp('mix', 'pod')); // pox mid
console.log(mixUp('dog', 'dinner')); // dig donner
You can get the Nth character, or letter, from a string by writing "string"[N]. The returned value will be a string containing only one character (for example, "b"). The first character has position 0, which causes the last one to be found at position string.length - 1. In other words, a two-character string has length 2, and its characters have positions 0 and 1.
Write a function countBs
that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters there are in the string.
Next, write a function called countChar
that behaves like countBs, except it takes a second argument that indicates the character that is to be counted (rather than counting only uppercase “B” characters). Rewrite countBs to make use of this new function.
console.log(countBs("BBC")); // 2
console.log(countChar("kakkerlak", "k")); // 4
Solution
function countBs(inputString) {
let charCounter = 0;
for (const char of inputString) {
if (char === 'B') {
charCounter += 1;
}
}
return charCounter;
}
console.log(countBs("BBC")); // 2
function countChar(inputString, targetChar) {
let count = 0;
for (const char of inputString) {
if (char === targetChar) {
count += 1;
}
}
return count;
}
console.log(countChar("kakkerlak", "k")); // 4
Not Bad
- Create a function called
notBad
that takes a single argument, a string. - It should find the first appearance of the substring 'not' and 'bad'.
- If the 'bad' follows the 'not', then it should replace the whole 'not'...'bad' substring with 'good' and return the result.
- If it doesn't find 'not' and 'bad' in the right sequence (or at all), just return the original sentence.
For example:
notBad('This dinner is not that bad!'): 'This dinner is good!'
notBad('This movie is not so bad!'): 'This movie is good!'
notBad('This dinner is bad!'): 'This dinner is bad!'
Solution
function notBad(inputStr) {
const indexOfNot = inputStr.indexOf('not');
const indexOfBad = inputStr.indexOf('bad!');
if (indexOfNot === -1 || indexOfBad === -1) {
return inputStr;
}
if (indexOfNot < indexOfBad) {
let sliceToReplace = inputStr.slice(indexOfNot, indexOfBad + 4);
inputStr = inputStr.replace(sliceToReplace, 'good!')
}
return inputStr;
}
console.log(notBad('This dinner is not that bad!')); // 'This dinner is good!'
console.log(notBad('This movie is not so bad!')); // 'This movie is good!'
console.log(notBad('This dinner is bad!')); // 'This dinner is bad!'
console.log(notBad('This dinner is not!')); // 'This dinner is not!'