JavaScript Strings
Write a JavaScript program to reverse a string
Description: Reverse the string “JavaScript”.
Hint:
- Split the string into an array of characters, reverse it and join it back.
JavaScript program to reverse a string
const text = "JavaScript";
// 1. split, reverse, join
console.log(text.split("").reverse().join(""));
// 2. loop
let result = "";
for (const ch of text) {
result = ch + result;
}
console.log(result);
Output:
Tutorials Class - Output Window
tpircSavaJ
tpircSavaJ
How it works
- Strings cannot be reversed directly, because they have no
reverse()method, but arrays do. - In the loop each new character is added to the front of the result.
Read JavaScript Strings.
Write a JavaScript program to check palindrome string
Description: Check if the words “madam”, “Level” and “hello” are palindromes.
Hint:
- A palindrome reads the same backwards.
- Change the text to lowercase first.
JavaScript palindrome program
function isPalindrome(text) {
const clean = text.toLowerCase();
return clean === clean.split("").reverse().join("");
}
for (const w of ["madam", "Level", "hello"]) {
console.log(w + (isPalindrome(w) ? " is a palindrome" : " is not a palindrome"));
}
Output:
Tutorials Class - Output Window
madam is a palindrome
Level is a palindrome
hello is not a palindrome
How it works
toLowerCase()makes “Level” equal to “level”.- The text is compared with its reverse.
Write a JavaScript program to count vowels in a string
Description: Count the vowels in “Tutorials Class”.
Hint:
- Vowels are a, e, i, o and u.
match()with thegflag returns all matches, ornullif none.
JavaScript program to count vowels
const text = "Tutorials Class";
const matches = text.toLowerCase().match(/[aeiou]/g);
console.log("Vowels:", matches ? matches.length : 0);
Output:
Tutorials Class - Output Window
Vowels: 5
How it works
/[aeiou]/gfinds every vowel.- If there is no vowel,
match()returnsnull, so we check it first.
Read Regular Expressions.
Write a JavaScript program to count the frequency of words in a sentence
Description: Count each word of the sentence “to be or not to be”.
Hint:
- Split the sentence into words.
- Use an object where the word is the key and the count is the value.
JavaScript word frequency program
const sentence = "to be or not to be";
const counts = {};
for (const word of sentence.split(" ")) {
counts[word] = (counts[word] || 0) + 1;
}
console.log(counts);
Output:
Tutorials Class - Output Window
{ to: 2, be: 2, or: 1, not: 1 }
How it works
counts[word] || 0gives 0 for a new word, and then 1 is added.- Objects keep the order in which keys were added.