Yumiko
Yumiko

Reputation: 468

Javascript, string, RegEx, if and else if, console.log different output

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

Upvotes: 0

Views: 296

Answers (2)

jvanstry
jvanstry

Reputation: 411

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)

Upvotes: 1

Zaenille
Zaenille

Reputation: 1384

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.

Upvotes: 1

Related Questions