jesnicka jesnicka - 18 days ago 9
Javascript Question

Finding the index of a character - JavaScript

I understand how to find the first occurrence of a character in a string using indexOf(). E.g.

Str.indexOf("a");


But how would I find the first occurrence of any character from an array of characters?

my code is:

function translatePigLatin(str) {

var vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];

for (var i = 0; i < vowels.length; i++) {
if (vowels[i] === str.charAt(0)) {
return str + "way";
} else {
return str.substr(0, str.indexOf(vowels[i]));
}
} return str;
}


I would like to end the substring at the first occurance of a vowel. Is there an easy method to do this?

Thanks in advance!

Answer

You can use String.search with a regex:

var vowels = /[aeiou]/i;

console.log('test'.search(vowels));
console.log('cherry'.search(vowels));
console.log('apricot'.search(vowels));


You can integrate it in your code like this:

function translatePigLatin(str) {
  var vowels = /[aeiou]/i;
  if (str.charAt(0).match(vowels)) {
    return str + "way";
  } else {
    return str.substr(0, str.search(vowels));
  }
}

console.log(translatePigLatin('cherry'));
console.log(translatePigLatin('apricot'));
console.log(translatePigLatin('test'));

I assume this is not the final version of the function and there's still some logic to be implemented.

Comments