I'm trying to add 'av' between consonant and vowel, but only if after one consonant I have one vowel.
Example:
'Hello all' will be something like 'Havellavo all'.
I have tried this code:
let text =
"Il vous faut pour cet exercice, traduire le texte suivant en Javanais. Pour se faire, vous devez intégrer 'av' après chaque consonne suivi d'une voyelle";
let voyelle = /^[aeiou]$/;
const translate = (str) => {
let newStr = "";
for (let i = 0; i < str.length; i++) {
if (str[i] !== voyelle) {
newStr += str[i];
if (str[i + 1] === voyelle) {
newStr += "av";
}
}
}
return newStr;
};
console.log(translate(text));
This is not working and I don't know why. Can anyone give me some tips or give me one solution with the explanation?
I would do it this way :
This would look something like this.
const vowels = ['a', 'e', 'i', 'o', 'u', 'y']
// splitting text by char
function translate(text) {
const chars = text.split('')
for (let i = 1; i < chars.length; i++) {
if (vowels.includes(chars[i]) && chars[i - 1] !== " " && !vowels.includes(chars[i - 1])) {
chars[i] = "av" + chars[i]
}
}
return chars.join('')
}
console.log(translate('Hello world'))
console.log(translate('Hello all'))
Note : Here the uppercase won't work, it will only work with lower case vowels
In your case you were missing the String#includes method that checks if a char is in a string. str[i] !== voyelle couldn't work since your were comparing a char and an array
Alternatively you could use the power of regular expressions combined with the replace method:
const regex = /([bcdfghjklmnpqrstvwxz])([aeiouy])/gi;
const translate = (text) => text.replace(regex, "$1av$2");
console.log(translate('Hello world'))
console.log(translate('Hello all'))
The regular expression matches a consonant followed by a vowel. The replacement expression references this consonant with $1 -- since it is captured in the first capture group (cf. parentheses in the regular expression) -- and the vowel with $2. So for instance, He is matched and replaced by Have ($1 is H and $2 is e) and lo is matched and replaced by lavo.
'av' string at the index positions. We go in reverse order so the index values won't change as the array grows.const translate = (str) => {
let regex = /(?<=[bcdfghjklmnpqrstvwxyz])[aeiou](?![aeiou])/gi;
let match;
let indices = [];
while ((match = regex.exec(str))) {
indices.push(match.index);
}
// Store indices in reversed order, highest to lowest
indices.reverse();
let strarr = str.split("");
for (let index of indices) {
// Insert 'av' at each index, starting from the end so the earlier indices don't change
strarr.splice(index, 0, "av");
}
return strarr.join("");
}
console.log(translate('Hello all'));
console.log(translate("Il vous faut pour cet exercice, traduire le texte suivant en Javanais. Pour se faire, vous devez intégrer 'av' après chaque consonne suivi d'une voyelle"));