0

I have an if else statement to match a string with vowels and consonants which works fine. I would like to tidy it up with a switch statement however using match() does not work as a case. what am i missing?

if else //returns vowels: 1, consonants: 3

function getCount(words) {
  var v,
      c;
    if (words === '' || words === ' ') { 
      v=0;
      c=0;
    } else if(words.match(/[aeiou]/gi)) {
        v = words.match(/[aeiou]/gi).length;
        c = words.replace(/\s|\W/g, '').split("").length - v;
    } else {
        v = 0;
        c = 0;
    }
    return {
      vowels: v,
      consonants: c
    };
}

getCount('test');

switch //returns vowels: 0, consonants: 0

function getCount(words) {
  var v,
      c;
    switch(words) {
      case words.match(/[aeiou]/gi):
        v = words.match(/[aeiou]/gi).length;
        c = words.replace(/\s|\W/g, '').split("").length - v;
        console.log("true");
        break;
      case '':
      case ' ':
        v = 0;
        c = 0;
        break;
      default:
        v = 0;
        c = 0;
    }
    return {
      vowels: v,
      consonants: c
    };
}

getCount('test');

2 Answers 2

2

// Code goes here

function getCount(words) {
  var v,
      c;
    switch(true) {
      case ( words.match(/[aeiou]/gi) !=null ):
        v = words.match(/[aeiou]/gi).length;
        c = words.replace(/\s|\W/g, '').split("").length - v;
        console.log("true");
        break;
      case (words==''):
      case (words==' '):
        v = 0;
        c = 0;
        break;
      default:
        v = 0;
        c = 0;
    }
    return {
      vowels: v,
      consonants: c
    };
}

console.log(getCount('test'));

Sign up to request clarification or add additional context in comments.

1 Comment

Explanation maybe?
1

Your switch statement needs to evaluate an expression and compare the result to the value of each case statement.

function getCount(words) {
  var v,
      c;
    switch(words.match(/[aeiou]/gi).length > 0) {
      case true:
        v = words.match(/[aeiou]/gi).length;
        c = words.replace(/\s|\W/g, '').split("").length - v;
        console.log("true");
        break;
      default:
        v = 0;
        c = 0;
    }
    return {
      vowels: v,
      consonants: c
    };
}

getCount('test');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.