Files
AP-Computer-Principles-Archive/StringChanllenge.js
2025-10-27 11:49:47 -05:00

56 lines
2.2 KiB
JavaScript

/*
QUOTE: I have a dream that my four little children will one day live
in a nation where they will not be judged by the color of
their skin but by the content of their character.
*/
let meow = "I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character."
// Function getFrequency takes as parameters two strings, text and token.
// This function needs to return the number of times a token accurs in text
// For example, if this function is tested with above quote and token is
// "will", then this function should return 2 becuase "will" occurs twice in
// the text
function getFrequency(text, token) {
let count = 0;
let words = text.split(" "); // Changed from text.split("")
for (let i=0; i<words.length; i++) {
let word=words[i]
if (word === token) {
count++;
}
}
return count;
}
console.log(getFrequency(meow, "will"));
// Function search takes as parameters two strings, text and token.
// This function needs to return the location where token occurs
// in parameter text. For example, if you call this function with
// token = "dream", this function will return 9. If token does not exist
// in text this function should return -1
function search(text, token){
return text.indexOf(token)
}
console.log(search(meow, "dream"))
// Function spellWord takes as parameters two strings, text and word.
// This function needs to return a spell of parameter word. For example,
// if you call this function with token = "children", this function should
// return c,h,i,l,d,r,e,n
// If word does not exist in text, this function should return "Word not found"
function spellWord(text, word) {
const words = text.split(" ").filter(s => s.length > 0);
const lowercaseWords = words.map(w => w.toLowerCase());
const lowerCaseWord = word.toLowerCase();
if (lowercaseWords.includes(lowerCaseWord)) {
return word.split("").join(",");
} else {
return "Word not found";
}
}
console.log(spellWord(meow, "children"))
// write code to test your functions