Sort Strings: Difference between revisions
Appearance
No edit summary |
No edit summary |
||
| Line 1: | Line 1: | ||
<h1> | <h1>Javascript Examples</h1> | ||
<code> | |||
// 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; | |||
} | |||
</code> | |||
// 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);<code> | |||
SORT words in alphabetical order | |||
*// take input | *// take input | ||
*const string = prompt('Enter a sentence: '); | *const string = prompt('Enter a sentence: '); | ||
| Line 10: | Line 39: | ||
*for (const element of words) { | *for (const element of words) { | ||
* console.log(element); | * console.log(element); | ||
} | }</code> | ||
Revision as of 18:28, 7 January 2026
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);
}