-4

If i have 'var' how can i get "e,o,o" out of it ? With substring you can only get the position

var str = "Hello world!";
var res = str.substring(1, 4);
Serigne Mbaye
  • 11
  • 1
  • 2
  • Check every character a.k.a. a loop. – Andreas Oct 23 '20 at 16:19
  • do you mean from **"Hello word!"** you want **"Hll wrd!"**, if yes, you have to check every char in the whole string if it is a vowel, delete it: [remove-a-character-from-a-string-using-javascript](https://stackoverflow.com/questions/9932957/how-can-i-remove-a-character-from-a-string-using-javascript) – ibra Oct 23 '20 at 16:23
  • Try this `var str = "Hello world!", vls={a:1,e:1,i:1,o:1,u:1}, res = str.split('').filter(ch => !!vls[ch]);` and close the question. You should research first. – Sajeeb Ahamed Oct 23 '20 at 16:28

5 Answers5

5

It's not entirely clear if you only want the vowels or if you want all except the vowels. Either way, a simple regular expression can get the characters you need.

let str = "Hello World";

let res = str.match(/[aeiou]/ig).join("");
console.log(res);

let res2 = str.match(/[^aeiou]/ig).join("");
console.log(res2);

Remove the .join("") part if you want an array, otherwise this gives you a string

ATD
  • 1,344
  • 1
  • 4
  • 8
1

How about:

var str = "Hello world!";
var theGoods = str.split('').filter(c => ['e', 'o'].includes(c)).join('');

Or if you wanted the 'inverse' behavior

var str = "Hello world!";
var theGoods = str.split('').filter(c => !['e', 'o'].includes(c)).join('');
The Dembinski
  • 1,469
  • 1
  • 15
  • 24
  • 1
    4 function calls, and two of them will iterate over the complete array/string, just to find a subset of vowels in a string – Andreas Oct 23 '20 at 16:24
  • \o.o/ I don't know if thats a criticism - but I think it's beautiful. I'm sticking with it. – The Dembinski Oct 23 '20 at 16:26
1

You can loop the string and store those vowels in an array.

var arr = [];
for(var i = 0; i < str.length; i++){
    if(str[i] == 'e' || str[i] == 'o'){
        arr.push(str[i]);
    }
}
console.log(arr);}
lyzaculous
  • 21
  • 3
1

It's pretty easy to extract them, as long as you know RegEx (regular expression)

var str = "Hello world!" // The original string
var res = str.match(/[aeiou]/gi).join("") // Extracting the vowels
// If you want to get the consonants, here you go.
var res2 = str.match(/[^aeiou]/gi).join("")
// Logging them both
console.log(res)
console.log(res2)
0
function deletevowels(str) {
    let result = str.replace(/[aeiou]/g, '')
    return result
}
  
var text = "Hi test of Replace Javascript";
const a = deletevowels(text);
console.log(a);
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30