Jump to content

Sort Strings

From Drywall Wiki
Revision as of 18:28, 7 January 2026 by Jlebeau81 (talk | contribs)

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);

}