Sort Strings
Appearance
Javascript Examples
// program to check the number of occurrence of a character
function countString(str, letter) {
let count = 0;
// looping through the items
for (let i = 0; i < str.length; i++) {
// check if the character is at that position
if (str.charAt(i) == letter) {
count += 1;
}
}
return count;
}
// take input from the user
const string = prompt('Enter a string: ');
const letterToCheck = prompt('Enter a letter to check: ');
//passing parameters and calling the function const result = countString(string, letterToCheck);
// displaying the result
console.log(result);
SORT words in alphabetical order
- // take input
- const string = prompt('Enter a sentence: ');
- // converting to an array
- const words = string.split(' ');
- // sort the array elements
- words.sort();
- // display the sorted words
- console.log('The sorted words are:');
- for (const element of words) {
- console.log(element);
}