Counting number of vowels in a string with JavaScript - javascript

I'm using basic JavaScript to count the number of vowels in a string. The below code works but I would like to have it cleaned up a bit. Would using .includes() help at all considering it is a string? I would like to use something like string.includes("a", "e", "i", "o", "u") if at all possible to clean up the conditional statement. Also, is it needed to convert the input into a string?
function getVowels(str) {
var vowelsCount = 0;
//turn the input into a string
var string = str.toString();
//loop through the string
for (var i = 0; i <= string.length - 1; i++) {
//if a vowel, add to vowel count
if (string.charAt(i) == "a" || string.charAt(i) == "e" || string.charAt(i) == "i" || string.charAt(i) == "o" || string.charAt(i) == "u") {
vowelsCount += 1;
}
}
return vowelsCount;
}

You can actually do this with a small regex:
function getVowels(str) {
var m = str.match(/[aeiou]/gi);
return m === null ? 0 : m.length;
}
This just matches against the regex (g makes it search the whole string, i makes it case-insensitive) and returns the number of matches. We check for null incase there are no matches (ie no vowels), and return 0 in that case.

Convert the string to an array using the Array.from() method, then use the Array.prototype.filter() method to filter the array to contain only vowels, and then the length property will contain the number of vowels.
const countVowels = str => Array.from(str)
.filter(letter => 'aeiou'.includes(letter)).length;
console.log(countVowels('abcdefghijklmnopqrstuvwxyz')); // 5
console.log(countVowels('test')); // 1
console.log(countVowels('ddd')); // 0

function countVowels(subject) {
return subject.match(/[aeiou]/gi).length;
}
You don't need to convert anything, Javascript's error handling is enough to hint you on such a simple function if it will be needed.

Short and ES6, you can use the function count(str);
const count = str => (str.match(/[aeiou]/gi) || []).length;

This could also be solved using .replace() method by replacing anything that isn't a vowel with an empty string (basically it will delete those characters) and returning the new string length:
function vowelCount(str) {
return str.replace(/[^aeiou]/gi, "").length;
};
or if you prefer ES6
const vowelCount = (str) => ( str.replace(/[^aeiou]/gi,"").length )

You can convert the given string into an array using the spread operator, and then you can filter() the characters to only those which are vowels (case-insensitive).
Afterwards, you can check the length of the array to obtain the total number of vowels in the string:
const vowel_count = string => [...string].filter(c => 'aeiou'.includes(c.toLowerCase())).length;
console.log(vowel_count('aaaa')); // 4
console.log(vowel_count('AAAA')); // 4
console.log(vowel_count('foo BAR baz QUX')); // 5
console.log(vowel_count('Hello, world!')); // 3

You can use the simple includes function, which returns true if the given array contains the given character, and false if not.
Note: The includes() method is case sensitive. So before comparing a character convert it to lowercase to avoid missing all the possible cases.
for (var i = 0; i <= string.length - 1; i++) {
if ('aeiou'.includes(string[i].toLowerCase())) {
vowelsCount += 1;
}
}

Use this function to get the count of vowels within a string. Works pretty well.
function getVowelsCount(str)
{
//splits the vowels string into an array => ['a','e','i','o','u','A'...]
let arr_vowel_list = 'aeiouAEIOU'.split('');
let count = 0;
/*for each of the elements of the splitted string(i.e. str), the vowels list would check
for any occurence and increments the count, if present*/
str.split('').forEach(function(e){
if(arr_vowel_list.indexOf(e) !== -1){
count++;} });
//and now log this count
console.log(count);}
//Function Call
getVowelsCount("World Of Programming");
Output for the given string would be 5. Try this out.
//Code -
function getVowelsCount(str)
{
let arr_vowel_list = 'aeiouAEIOU'.split('');
let count = 0;
str.split('').forEach(function(e){
if(arr_vowel_list.indexOf(e) !== -1){
count++;} });
console.log(count);
}

Use match but be careful as it can return a null if no match is found. This solves it:
const countVowels = (subject => (subject.match(/[aeiou]/gi) || []).length);

function vowels(str) {
let count=0;
const checker=['a','e','i','o','u'];
for (let char of str.toLowerCase){
if (checker.includes(char)) {
count++;
}
return count;
}
function vowels(str) {
const match = str.match(/[aeiou]/gi);
return match ? match.length : 0 ;
}

count = function(a) {
//var a=document.getElementById("t");
console.log(a); //to see input string on console
n = a.length;
console.log(n); //calculated length of string
var c = 0;
for (i = 0; i < n; i++) {
if ((a[i] == "a") || (a[i] == "e") || (a[i] == "i") || (a[i] == "o") || (a[i] == "u")) {
console.log(a[i]); //just to verify
c += 1;
}
}
document.getElementById("p").innerText = c;
}
<p>count of vowels </p>
<p id="p"></p>
<input id="t" />
<input type="button" value="count" onclick="count(t.value)" />

This is the shortest solution
function getCount(str) {
return (str.match(/[aeiou]/ig)||[]).length;
}

const containVowels = str => {
const helper = ['a', 'e', 'i', 'o', 'u'];
const hash = {};
for (let c of str) {
if (helper.indexOf(c) !== -1) {
if (hash[c]) {
hash[c]++;
} else {
hash[c] = 1;
}
}
}
let count = 0;
for (let k in hash) {
count += hash[k];
}
return count;
};
console.log(containVowels('aaaa'));

As the introduction of forEach in ES5 this could be achieved in a functional approach, in a more compact way, and also have the count for each vowel and store that count in an Object.
function vowelCount(str){
let splitString=str.split('');
let obj={};
let vowels="aeiou";
splitString.forEach((letter)=>{
if(vowels.indexOf(letter.toLowerCase())!==-1){
if(letter in obj){
obj[letter]++;
}else{
obj[letter]=1;
}
}
});
return obj;
}

My solution:
const str = "In West Philadephia, born and raised.";
const words = str.split("");
function getVowelCount() {
return words.filter(word => word.match(/[aeiou]/gi)).length;
}
console.log(getVowelCount());
Output: 12

You can easily solve this using simple regex. match() method matches string agains a regex variable. return an array if the is a matches and return null if no match is found.
function getVowels(str) {
let vowelsCount = 0;
const regex = /[aiueo]/gi;
vowelsCount = str.match(regex);
return vowelsCount ? vowelsCount.length : 0;
}
console.log(getVowels('Hello World')) => return 3
console.log(getVoewls('bbbcccddd') => return 0

Just use this function [for ES5] :
function countVowels(str){
return (str.match(/[aeiou]/gi) == null) ? 0 : str.match(/[aeiou]/gi).length;
}
Will work like a charm

(A)
const countVowels = data => [...data.toLowerCase()].filter(char => 'aeiou'.includes(char)).length;
(B)
const countVowels = data => data.toLowerCase().split('').filter(char => 'aeiou'.includes(char)).length;
countVowels("Stackoverflow") // 4

The following works and is short:
function countVowels(str) {
return ( str = str.match(/[aeiou]/gi)) ? str.length : 0;
}
console.log(countVowels("abracadabra")); // 5
console.log(countVowels("")); // 0

One more method (using reduce):
function getVowels(str) {
return Array.from(str).reduce((count, letter) => count + 'aeiou'.includes(letter), 0);
}

Here is the my solution for the problem:
function getVowelsCount(s) {
let vowels = ["a", "e", "i", "o", "u"];
let count=0;
for(let v of s) {
if(vowels.includes(v)){
console.log(v);
count=count+1;
}
}
console.log(count);
}

After research and without using regex, this is what I found the simplest to understand for new devs like me.
function vowelCount (string) {
let vowel = "aeiouy"; // can also be array
let result = 0;
for (let i = 0; i < string.length; i++) {
if (vowel.includes(string[i].toLowerCase())) {
result++;
}
}
return result;
}
console.log(vowelCount("cAkeYE"));

function vowelCount(str){
str=str.toLowerCase()
let count=[]
for(let i=0;i<str.length;i++){
if(str.charAt(i)=='u'||str.charAt(i)=='o'||str.charAt(i)=='i'||str.charAt(i)=='e'||str.charAt(i)=='a'){
count.push(str.charAt(i))//to store all the vowels in an array
}
}
let eachcount={}
count.forEach((x)=>eachcount[x]?eachcount[x]++:eachcount[x]=1) //to count each vowel from the count array
return eachcount
}
console.log(vowelCount("hello how Are You"))

function vowelsCount(sentence) {
let vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
let count = 0;
let letters = Array.from(sentence);
letters.forEach(function (value) {
if (vowels.includes(value)) {
count++
}
})
return count;
}
console.log(vowelsCount("StackOverFlow"));

Another solution using Set to lookup characters in constant time and reduce() to do the actual counting. The implementation also uses the spread syntax for string as strings are Iterable.
/**
* Count vowels in a string. Ignores case.
* #param {string} str String to count the vowels in
* #returns numbers of vowels
*/
function countVowels(str) {
let vowels = new Set("aeiou")
return [...str.toLowerCase()].reduce((count, character) => count + vowels.has(character) || 0, 0)
};
console.log(countVowels("apple"))
console.log(countVowels("pears are yummy"))
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

create a unique key from 3 Alphabet

I'm trying to create a unique key using the alphabets;
I've managed to work it out but I don't really like the approach I took. and I believe someone out there might be able to help me get a better way to do this code. Please let me know if you think of a better idea? or whatever your idea to compare with mine?
I think this might be a good way to share knowledge .. Thanks in advance
let string = 'ABE';
let ar1 = ["A", "B", "C", "D", "E"];
string = string.split('');
if (string[2] !=='E') {
for (let i = 0; i < 5; i++) {
if (string[2] === ar1[i]) {
i = i+1;
string[2] = ar1[i]
}
}
string = string.toString().replace(/,/g, '');
console.log("case 1", string);
} else if (string[1] !=='E' && string[2] ==='E') {
string[2] ='A';
for (let i = 0; i < 5; i++) {
if (string[1] === ar1[i]) {
i = i+1;
let newString = ar1[i];
console.log(ar1[i]);
string[1] = newString;
}
}
string = string.toString().replace(/,/g, '');
console.log("case 2", string);
} else if (string[1] ==='E' && string[2] ==='E') {
string[1] ='A';
string[2] ='A';
for (let i = 0; i < 5; i++) {
if (string[0] === ar1[i]) {
i = i+1;
string[0] = ar1[i];
}
}
string = string.toString().replace(/,/g, '');
console.log("case 3", string);
}
Results would be like:
if string = "AAA" Then the result "AAB"
if string = "AAE" Then result will be "ABA"
if string = "AEE" Then result will be "BAA"
You could encode the value to a numerical value, like this palce value
36 6 1
C B A
2 1 0 78
and encode an incremented value with the wanted characters and length.
function decode(value, characters) {
const
values = Object.fromEntries(Array.from(characters, (v, i) => [v, i]));
return value
.split('')
.reduce((s, v) => s * characters.length + values[v], 0);
}
function encode(value, characters, length = 0) {
let result = '';
do {
result = characters[value % characters.length] + result;
value = Math.floor(value / characters.length);
} while (value);
return result.padStart(length, characters[0]);
}
console.log(decode('AAA', 'ABCDEF')); // 0
console.log(encode(0, 'ABCDEF', 3)); // AAA
console.log(encode(1, 'ABCDEF', 3)); // AAB
console.log(decode('CBA', 'ABCDEF')); // 78
console.log(encode(78, 'ABCDEF', 3)); // CBA
console.log(encode(79, 'ABCDEF', 3)); // CBB
This approach rotates each character by a fixed amount (which could be improved upon), ignoring the other characters.
let ar1 = ["A", "B", "C", "D", "E"];
function scramble(str) {
let rotation=3;
let s = str.split('');
for (let i=0; i<s.length; i++) {
s[i]=ar1[(parseInt(s[i],16)+rotation) % ar1.length];
}
return s.toString().replace(/,/g, '');
}

How to remove only one of repeated chars in string using JavaScript

I have a string with repeated chars like : 'CANADA'.
And I am trying to get the string which removed only one of repeated chars :
'CNADA', 'CANDA', 'CANAD'.
I've tried it with subString, but it returned the part of string removed.
Also I've tried it with reduce, but it ended up removing all the repeated chars ('CND').
What is the way of removing only one char at time?
The results can be stored in array. (results = ['CNADA', 'CANDA', 'CANAD'])
Thank you.
You can achieve this by utilizing the second parameter of String#indexOf() which specifies the position from which to start the search. Here in a while loop, and using a Set to remove dulplicates before returning.
function getReplaceOptions(str, char) {
let res = [], i = str.indexOf(char, 0);
while (i !== -1) {
res.push(str.substring(0, i) + str.substring(++i));
i = str.indexOf(char, i)
}
return Array.from(new Set(res))
}
console.log(getReplaceOptions('CANADA', 'A'));
console.log(getReplaceOptions('Mississippi', 's'));
You can first count all the occurrences in the string. Later you can iterate over the script and if the count is greater than 1 you can remove that character.
const theString = 'CANADA'
const letterCount = {}
const resultArr = []
for (var i = 0; i < theString.length; i++) {
const theLetter = theString.charAt(i)
if(letterCount[theLetter]){
letterCount[theLetter] = letterCount[theLetter] + 1
}
else{
letterCount[theLetter] = 1
}
}
console.log(letterCount)
for (var i = 0; i < theString.length; i++) {
const theLetter = theString.charAt(i)
if(letterCount[theLetter] && letterCount[theLetter] > 1){
resultArr.push(theString.substr(0, i) + theString.substr(i + 1))
}
}
console.log(resultArr)
If you want to remove only the first repeating character then you can use matchAll here as:
Just see the browser compatibility before using this
const str = 'CANADA';
const firstRepeatedChar = 'A';
const result = [];
for (let { index } of str.matchAll(firstRepeatedChar)) {
result.push(str.slice(0, index) + str.slice(index + 1));
}
console.log(result);
NOTE: If you want to search for the first repeating character then remove it, then you can do as:
const str = 'CANADA';
let firstRepeatedChar = '';
const set = new Set();
for (let i = 0; i < str.length; ++i) {
if (!set.has(str[i])) {
set.add(str[i]);
} else {
firstRepeatedChar = str[i];
break;
}
}
const result = [];
for (let { index } of str.matchAll(firstRepeatedChar)) {
result.push(str.slice(0, index) + str.slice(index + 1));
}
console.log(result);
You could use some Array magic to remove duplicate characters:
function removeDuplicateCharacters(value) {
// convert string to array and loop through each character
return String(value).split('').filter(function(char, index, all) {
// return false if char found at a different index
return (index === all.indexOf(char));
})
.join(''); // convert back to a string
}
// returns `CAND`
removeDuplicateCharacters('CANADA');
// returns `helo wrd`
removeDuplicateCharacters('hello world');

How to find the longest common prefix in an array of strings?

I'm trying to solve this using the .every method but it's not returning true and therefore it's not adding onto my string and I'm not sure why.
var longestCommonPrefix = function(arr) {
if (arr.length === 0) {
return undefined;
}
let result = '';
for (let i = 0; i < arr.length; i++) {
if (arr.every(x => arr[i].charAt(i) === x)) {
result += arr[i].charAt(i);
}
}
return result
}
console.log(longestCommonPrefix(["flower", "flow", "flight"])); //fl
You need to iterate over one string, not over the whole array: check if the first character of the string is present everywhere, then the second character, etc:
var longestCommonPrefix = function(arr) {
if (arr.length === 0) {
return undefined;
}
let result = '';
for (let i = 0; i < arr[0].length; i++) {
if (arr.every(x => x.charAt(i) === arr[0][i])) {
result += arr[i].charAt(i);
} else break;
}
return result;
}
console.log(longestCommonPrefix(["flower", "flow", "flight"])); //fl
Your use of Array.every is along the right lines. You want to check that every string in the array has the same character at position i. I think you got confused when you named the parameter x, when it is in fact a string :)
var longestCommonPrefix = function(words) {
if (words.length === 0) {
return "";
}
const letters = [];
const lengthOfShortestWord = Math.min(...words.map(word => word.length));
for (let i = 0; i < lengthOfShortestWord; i++) {
const char = words[0][i];
if (words.every(word => word[i] === char)) {
letters.push(char);
} else {
break;
}
}
return letters.join("");
}
console.log(longestCommonPrefix(["flower", "flow", "flight"])); //fl
Unless I am mistaken the longest prefix is never going to be greater than the smallest string in the array.
In this case "fl" is both the smallest string and the longest common prefix:
["flower", "fl", "flight"]
So start with finding the smallest string in arr:
let [sm] = [...arr].sort((a, b) => a.length - b.length);
Then check that all strings in arr start with sm:
arr.every(str => str.startsWith(sm));
If that isn't the case then shorten sm by one character:
sm = sm.slice(0, -1);
And keep going until you eventually find the longest prefix or sm becomes an empty string:
const prefix = arr => {
let [sm] = [...arr].sort((a, b) => a.length - b.length);
while (sm && !arr.every(str => str.startsWith(sm))) sm = sm.slice(0, -1);
return sm;
};

Why isn't my for loop incrementing and why isn't my splice being changed?

I came across a problem that seemed very straightforward, but as I coded more some of my expected return were not as I expected.
Any help is appreciated. If you do provide any help please explain your approach and how I got stuck.
The problem:
We're given a string and need to see if it can be broken down into words from a dictionary array. For example:
const str = "applecomputer";
const dictArr = ["apple", "computer"];
stringBreakdown(str, dictArr);
// true
Assuming that there are no repeats in the dictionary array, can you write a method that will return true if the string can be broken down into words from the array, or false if not?
The two test cases:
Expect stringBreakdown('crazyrichasians', [ 'crazy', 'rich', 'asians' ]) // to return true
Expect stringBreakdown('lockcombination', [ 'lock', 'combo' ]) // to return false
My code and approach:
Create a hash map of all the characters in the string
Create a helper function remove charters from each string in the array
As I remove the character in the string I will also decrease each time I've seen that letter from the hash map
If I seen all the letters in that string then I will remove it from the given array
Lastly, if the given array length is less than 0, return true because I was able to make all of the word or turn false because more words are in the array
const stringBreakdown = (str, dictArr)=> {
let hashDictionary = {};
let shouldRemoveWord
for(let x = 0; x <= str.length-1;x++){
!hashDictionary[str[x]] ? hashDictionary[str[x]] =1 : hashDictionary[str[x]]+=1
}
for(let y = 0; y < dictArr.length;y++ ){
shouldRemoveWord = removeLetters(hashDictionary,dictArr[y])
if(shouldRemoveWord === true){
dictArr.splice(y,1)
}
}
console.log('dictArr',dictArr)
return dictArr.length > 0 ? true : false;
}
const removeLetters = (hash,word) =>{
let modifiedWord = word.split('')
for(let k = 0; k < modifiedWord.length;k++){
if(hash[word[k]]){
modifiedWord.splice(k,1)
hash[word[k]]-=1
}
}
return modifiedWord.join('').length < 0 ? true : false;
}
You can go over each word provided in the array then:
Firstly, check if the length of all the words combined together matches with the length of the string under test. If not return false.
Secondly, if the length matches, then check whether every word as a whole is included as a sub-string in the supplied string:
function stringBreakdown(str, dictArr){
return dictArr.join("").length === str.length
&&
dictArr.every(word => str.includes(word));
}
//tests
console.log(stringBreakdown('crazyrichasians', [ 'crazy', 'rich', 'asians' ]));
console.log(stringBreakdown('lockcombination', [ 'lock', 'combo' ]));
console.log(stringBreakdown('applecomputer', [ 'apple', 'computer']));
console.log(stringBreakdown('appelcomputer', [ 'apple', 'computer']));
console.log(stringBreakdown('appcolemputer', [ 'apple', 'computer']));
console.log(stringBreakdown('applecomputer', [ 'app', 'le', 'computer']));
Your approach is dubious as when you go through each character by character you are not looking at the word it forms i.e. in your case if applecomputer is the string and the array has ['appel', 'comterpu'] your algorithm will return true in this case.
It is because you are making a character map from the inout string str and then going through each word's character and decrementing the occurrence of it in the character map so the combination doesn't matter.
const stringBreakdown = (str, dictArr)=> {
let hashDictionary = {};
let shouldRemoveWord
for(let x = 0; x <= str.length-1;x++){
!hashDictionary[str[x]] ? hashDictionary[str[x]] =1 : hashDictionary[str[x]]+=1
}
for(let y = 0; y < dictArr.length;y++ ){
shouldRemoveWord = removeLetters(hashDictionary,dictArr[y])
if(shouldRemoveWord === true){
dictArr.splice(y,1)
}
}
return dictArr.length > 0 ? true : false;
}
const removeLetters = (hash,word) =>{
let modifiedWord = word.split('')
for(let k = 0; k < modifiedWord.length;k++){
if(hash[word[k]]){
modifiedWord.splice(k,1)
hash[word[k]]-=1
}
}
return modifiedWord.join('').length < 0 ? true : false;
}
//doesn't work outputs true
console.log(stringBreakdown('applecomputer', ['appel', 'computer']));
simply loop through the dictionary
const dictArr = ["lock", "combo"];
function checkInDic(val){
var len = 0;
dictArr.forEach(element => {
if(val.includes(element)){
len += element.length;
}else{
return false;
}
});
if(len == val.length){
return true;
}else{
return false;
}
}

While loop to print vowels and other elements on a new line in JavaScript

Trying to print any vowels from a word on a new line in the order they appear.
Then do the same for each constant after all the vowels have been printed.
I've tried using breaks and a switch case but the code wouldn't work.
function vowelsAndConsonants(s) {
var atom = s.length;
var i = 0;
while (i <= atom)
{
if (s[i] === 'a' || s[i] === 'e' || s[i] === 'i' || s[i] === 'o' || s[i] === 'u') {
console.log('\n' + s[i]);
}
else {
console.log('\n' + s);
}
}
}
I expect an output to be like:
a
i
o
Then the consonants in the order they appear:
t
p
r
You can use includes to check vowel array on given string
const vowelsAndconsonants = str => {
const vowels=['a','e','i','o','u'];
//convert string to array and get rid of non alphabets as we are just interested on consonants and vowel
const str_array=str.replace(/[^a-zA-Z]/g, '').split('');
//pluck vowels
const vowels_final=str_array.filter( a => vowels.includes(a.toLowerCase()));
//pluck consonants
const consonant_final=str_array.filter( a => !vowels.includes(a.toLowerCase()));
//to print any vowels from a word on a new line and then consonant in the order they appear.
return vowels_final.join('\n') + '\n' + consonant_final.join('\n');
}
console.log(vowelsAndconsonants('tEstOnlY and nothing else'))
console.log(vowelsAndconsonants('dry'))
console.log(vowelsAndconsonants('I love stackoverflow'))
function vowelsAndConsonants(s) {
let vowels = [];
let consonas = [];
for(var i=0; i<s.length ; i++) {
if((s[i]=='a')||(s[i]=='e')||(s[i]=='i')||(s[i]=='o')||(s[i]=='u')){
vowels.push(s[i])
} else {
consonas.push(s[i]);
}
}
let concatArr = [...vowels, ...consonas];
for (let i of concatArr) {
console.log(i);
}
}
Your main problem is that you are deciding wether or not you should print when checking each letter. The result output for that would actually be initial string.
While sumit's answer does the trick, this is the way I would do it, since it requires you to loop through the letters only once:
const vowelsAndConsonants = (str) => {
const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
// Check for vowels
var letters = str.split('');
var vowelsFound = [], consonantsFound = [];
for (var i in letters) {
if (vowels.includes(letters[i])) {
vowelsFound.push(letters[i]);
} else {
consonantsFound.push(letters[i]);
}
}
console.log("Vowels:", vowelsFound.join(""));
console.log("Consonants:", consonantsFound.join(""));
}
var str = "ThisIsATest";
vowelsAndConsonants(str);
So here is the final code that I used. Thank for the help Dash and summit. I combined both of their codes.
// This is the function with the parameter which will have the input.
function vowelsAndConsonants(s) {
// This lists, all the vowels. Since I know the input is all lowercase, there is no need for uppercase. A lowercase method could also be used.
const vowels = ['a', 'e', 'i', 'o', 'u'];
// The input is split up to avoid printing the entire string, and is stored in a variable.
var letters = s.split('');
// An array to hold the vowels is created.
var vowelsFound = [];
// An array to hold the consonants is created.
var consonantsFound = [];
// Loops through all the split up characters held in the letters variable.
for (var i in letters) {
// If statement tests by using include to see if any of vowels match the i looper.
if (vowels.includes(letters[i])) {
//If any vowels do match, then they get added to the end of the vowelsFound array,
which then get pushed up, so that it can be printed in the order they appear.
vowelsFound.push(letters[i]);
//The same process is used for the consonants.
} else {
consonantsFound.push(letters[i]);
}
}
//Prints the vowels in their order, on a new line for each character.
console.log(vowelsFound.join('\n'));
console.log(consonantsFound.join('\n'));
}
visit: https://www.w3schools.com/code/tryit.asp?filename=GQP0X4ZZEKNQ for finding result in better way.
With the help of bellow we can separates vowels and consonants with the easy way
let strOne = "javascriptloopsAI"; // take any string
//String convert into lower case
var str = strOne.toLowerCase();
let vowelarr = ['a','e','i','o','u']; // use vowels array
// here's we are splitting str string with space.
let strArr = [...str];
var html='';
var htmlV='';
//for loop for strArr
for (i = 0; i < strArr.length; i++)
{
let field='';
//for loop for vowelarr
for (j = 0; j < vowelarr.length; j++)
{
if(strArr[i]==vowelarr[j])
{
field=strArr[i];
htmlV += strArr[i]+'</br>' // adding only vowels in htmlv variable
}
}
if(strArr[i]!=field)
{
html += strArr[i]+'</br>' //adding only consonants in htmlv variable
}
}
document.getElementById("demo").innerHTML = htmlV;
document.getElementById("demo1").innerHTML = html;
<p id="demo"></p>
<p id="demo1"></p>
Hackerrank Day2 Solution:
function vowelsAndConsonants(s) {
//Create Array of vowels
const vowels = ["a","e","i","o","u"];
//Convert String to Array
const arr = s.split("");
//Empty vowels and cons array
var vowelsFound = [];
var cons = [];
//Push vowels and cons to their arrays
for (var i in arr) {
if (vowels.includes(arr[i])) {
vowelsFound.push(arr[i]);
} else {
cons.push(arr[i]);
}
}
//ConsoleLog so that they in order and cons follows vowels on new lines
console.log(vowelsFound.join('\n') + '\n' + cons.join('\n'))
}
//Test, Exclude in copy
vowelsAndConsonants(javascriptloops);
function vowelsAndConsonants(s){
let strC='';
for(var i=0; i<s.length ; i++)
{
if((s[i]=='a')||(s[i]=='e')||(s[i]=='i')||(s[i]=='o')||(s[i]=='u')){
console.log(s[i]);
}
else{
strC=strC.concat(s[i]).concat('\n');
}
}
console.log(strC)
}
vowelsAndConsonants('magic')
We can solve the problem using the below codes too. [ Hackerrank Day2 Solution ]
function vowelsAndConsonants(s) {
// Create an array of vowels
const vowels = ['a','e','i','o','u'];
// Split up the String and Convert it to an Array
const letters = s.split('');
// Check for vowels
for(let i in letters){
if(vowels.includes(letters[i])){
// Print vowels on a new line for each characters.
console.log(letters[i]);
}
}
// Check for consonants
for(let i in letters){
if(!(vowels.includes(letters[i]))){
// Print consonants on a new line for each characters.
console.log(letters[i]);
}
}
}
const test = "javascript";
vowelsAndConsonants(test);
HackerRank Day 2: Loops
function vowelsAndConsonants(s) {
let conso ="";
for(var i=0;i<s.length;i++){
if((s[i]=="a")||(s[i]=="e")||(s[i]=="i")||(s[i]=="o")||
(s[i]=="u")){
console.log(s[i])
}else{
conso += s[i]+"\n";
}
}
console.log(conso);
}
This question is already answered well. You can also use for of loops.
function vowelsAndConsonants(s) {
const vowels = [];
const consonants = [];
// Separating Vowels and Consonants
for (let ch of s){
if ((ch=='a')||(ch=='e')||(ch=='i')||(ch=='o')||(ch=='u')){
vowels.push(ch)
}else{
consonants.push(ch)
}
}
// Printing only Vowels
for (let v of vowels){
console.log(v)
}
// Printing only Consonants
for (let c of consonants){
console.log(c)
}
}
function vowelsAndConsonants(s) {
var a = s.length;
for (var i = 0; i < a; i++) {
if (s[i] == 'a' || s[i] == 'e' || s[i] === 'i' || s[i] == 'o' || s[i] == 'u') {
console.log(`${s[i]}`);
}
}
for (var j = 0; j < a; j++) {
if (s[j] == 'a' || s[j] == 'e' || s[j] === 'i' || s[j] == 'o' || s[j] == 'u') {
} else {
console.log(`${s[j]}`)
}
}
}
vowelsAndConsonants('function')
function vowelsAndConsonants(s) {
const vowel = ['a','e','i','o','u'];
let ourVowel = [];
let ourConsonant = [];
for(let i = 0; i < s.length; i++){
if(vowel.includes(s[i].toLowerCase())){
ourVowel.push(s[i]);
}else{
ourConsonant.push(s[i]);
}
}
ourVowel.forEach(e=>{
console.log(e);
});
ourConsonant.forEach(e=>{
console.log(e)
})
}
We can simply do this using regular expression to match vowels and consonants, and then print each of them.
Below is the working code snippet:
function vowelsAndConsonants(s) {
var vw =s.match(/[aeiouAEIOU]+?/g); //regular expression to match vowels
var con=s.match(/[^aeiouAEIOU]+?/g); //regular expression to not match vowels, ie. to match consonants
printOnConsole(vw); //print vowels
printOnConsole(con); //print consonants
}
//function to print values on console.
function printOnConsole(arrPrint){
for(var i=0;i<arrPrint.length;i++){
console.log(arrPrint[i]);
}
}

Categories

Resources