I'm trying to write a program that removes the first instance of each vowel from a string.
"the quick brown fox jumps over the lazy dog" becomes "th quck brwn fox jmps over the lzy dog"
This is what my code looked like before (Comments on the next one)
str = "the quick brown fox jumps over the lazy dog"
letters = ['a', 'e', 'i', 'o', 'u']
i = 0
j = 0
strArr = str.split('') // converts word to string
vowel = letters[i]
// replaceVowel = str.replace(letters.indexOf(i), '');
while (i < str.length || j == 5)
if (strArr[i] == letters[j] ) {
console.log('I found ' letters[j])
i = 0
j
}
else if (strArr[i] !== letters[j]){
i
}
strArr.join()
console.log(str);
My idea is to covert the string into an array with split, then compare the index of the string with the letters array [aeiou] and check for the first vowel. The first 'a' gets replaced with whitespace and then it checks for the next vowel ('e'). This occurs until j=5 as that's when the loop would exit after checking for 'u'
I then changed up my code as so:
str = "the quick brown fox jumps over the lazy dog"
letters = ['a', 'e', 'i', 'o', 'u']
index = 0
j = 0
strArr = str.split('') // converts word to string
vowel = letters[index]
while (index < strArr.length && j !== 5)
// Where j references the vowels
if (strArr[index] == letters[j]) {
strArr.splice(index, '')
index = 0
j
// j to cycle through vowels after the first
// instance has been repaced
}
else if (strArr[index] !== letters[j]){
index
// Cycle through the string until you find a vowel
}
else if (strArr[index] == str.length && j!== 6) {
index = 0
j
// If you hit the end of the string and couldn't find
// a vowel, move onto the next one
}
strArr.join()
console.log(str);
Nothing happens when I run it. I am wondering if there is a flaw in my logic?
If there is also an easier way to do this please do inform me.
Your guidance is greatly appreciated!
CodePudding user response:
I misunderstood the question to begin with but here is an example that simply iterates over an array of vowels and slices the first of each from the result string using String#indexOf()
to find the index and String#slice()
to cut around it.
const str = 'the quick brown fox jumps over the lazy dog';
let result = str;
for (const vowel of ['a', 'e', 'i', 'o', 'u']) {
const vowelIndex = result.indexOf(vowel);
result = result.slice(0, vowelIndex) result.slice(vowelIndex 1);
}
console.log(result);
// th qck brwn fox jumps over the lzy dog
CodePudding user response:
You can split the string by a space, then map
through the array.
To remove the vowel, convert the string into an array, and use findIndex
to find the first character which vowels
includes. Then, remove that item.
const str = `the quick brown fox jumps over the lazy dog`
const vowels = ['a', 'e', 'i', 'o', 'u']
const result = str.split(' ').map(e => {
const arr = [...e]
return arr.splice(arr.findIndex(c => vowels.includes(c)), 1), arr.join('')
})
console.log(result.join(' '))