You can create a function in JavaScript that removes vowels from a string and then returns the reversed version of the resulting string. Here’s an example implementation:
JavaScript Program:
function removeVowelsAndReverse(str) {
// Remove vowels using a regular expression
const withoutVowels = str.replace(/[aeiouAEIOU]/g, '');
// Reverse the string
const reversed = withoutVowels.split('').reverse().join('');
return reversed;
}
// Example usage
const inputString = "Hello World!";
const result = removeVowelsAndReverse(inputString);
console.log(result); // Output: "!dlrW llH"
Here’s a breakdown of the JavaScript code that removes vowels from a string and returns the reversed version:
function removeVowelsAndReverse(str) {
// Remove vowels using a regular expression
const withoutVowels = str.replace(/[aeiouAEIOU]/g, '');
// Reverse the string
const reversed = withoutVowels.split('').reverse().join('');
return reversed;
}
Breakdown:
Function Declaration:
function removeVowelsAndReverse(str): This defines a function named removeVowelsAndReverse that takes a single parameter str, which is the input string.
Remove Vowels:
const withoutVowels = str.replace(/[aeiouAEIOU]/g, '');
str.replace(...): This method replaces parts of the string.
/[aeiouAEIOU]/g: This is a regular expression that matches all vowels (both lowercase and uppercase).
'': This is the replacement string (empty), meaning all matched vowels will be removed.
The result is stored in the variable withoutVowels.
Reverse the String:
const reversed = withoutVowels.split('').reverse().join('');
withoutVowels.split(''): This splits the string into an array of individual characters.
.reverse(): This method reverses the array of characters.
.join(''): This joins the reversed array back into a single string.
The result is stored in the variable reversed.
Return the Result:
return reversed;: This returns the final reversed string without vowels.
Example Usage:
const inputString = "Hello World!";
const result = removeVowelsAndReverse(inputString);
console.log(result); // Output: "!dlrW llH"
In this example, the input string "Hello World!" will have its vowels removed to become "Hll Wrld!", which is then reversed to "!dlrW llH".
No comments:
Post a Comment