0

I want to output a string's vowels in order, so I decided to use RegEx to do it.

However, when I put the expression in different position in (if and else if), the output is different for the same expression. Could anyone explain?

function ordered_vowel_word(str) {

  if(str.match(/[aeiou]{1,}/g) !== ""){
  var arr = str.match(/[aeiou]{1,}/g);
      console.log(arr);
  }
  else
      console.log(str);
  }

ordered_vowel_word("bcg");
ordered_vowel_word("eebbscao");

/* The Output */

ordered_vowel_word("bcg");

==> null

ordered_vowel_word("eebbscao");

==> ["ee", "ao"]

But if I restructure the expression,

function ordered_vowel_word(str) {

  if(str.match(/[^aeiou]/) !== "")
      console.log(str); 
  else if(str.match(/[aeiou]{1,}/g) !== ""){
  var arr = str.match(/[aeiou]{1,}/g);
      console.log(arr); 
  }
}

The output will be

ordered_vowel_word("bcg");

==> bgv

ordered_vowel_word("eebbscao");

==> eebbscao

Dima Grossman
  • 2,800
  • 2
  • 21
  • 26
Yumiko
  • 448
  • 5
  • 16

2 Answers2

1

The return value of str.match the way you are using it is an array containing the matches when it matches. Also, it is not an empty string when there are no matches... it is actually null.

Try changing what you are testing for in your if condition to this:

str.match(/[aeiou]{1,}/g) !== null)
jvanstry
  • 411
  • 4
  • 10
1

Take note that string.match returns an array if there is at least one match, and it returns null if there is no match.

What I think you want is :

if(str.match(/[aeiou]{1,}/g) == null){ // no matches

or

if(str.match(/[aeiou]{1,}/g) != null){ //has a match

As for the sorting, you have to do process the array you get with str.match.

Check out this SO answer for sorting arrays. Yes, you can use > and < operators for characters.

Community
  • 1
  • 1
Zaenille
  • 1,384
  • 9
  • 16