0

This function should remove the vowels in string and return string without vowels

function removeVowels(string) {
    var newstring = '';
    var vowels = ['a','e','i','o','u'];
    for ( i in string) {
        if ( i.toLowerCase() not in vowels) { // I know this is wrong but is anything I can use instead of "not in" in JS?
            continue
        } else {
            newstring += i
        }
    }
    return newstring;
}
Kate Kiatsiri
  • 63
  • 2
  • 7
  • Be careful! The `in` operator doesn't work the same way in JS as it does in Python. It searches for *properties in objects*, and doesn't work as a generalized "containment" operator. (and no, there is no `not in `operator) – juanpa.arrivillaga Sep 22 '21 at 00:09
  • To invert a test in javascript, use ```if (!(condition))```. Your question is covered here in [Is there a “not in” operator in JavaScript for checking object properties?](https://stackoverflow.com/questions/7972446/is-there-a-not-in-operator-in-javascript-for-checking-object-properties) – sj95126 Sep 22 '21 at 00:12
  • Also very important: `for ( i in string)` **does not work the same way in JS as it does in Python**. You'd need to use `for (i of string)`... you really should take the time to learn Javascript for-loops on their own terms – juanpa.arrivillaga Sep 22 '21 at 00:13
  • You also need to declare the iterated variable `for (let i of string) {...` – pilchard Sep 22 '21 at 00:16
  • @pilchard well, in strict mode :) – juanpa.arrivillaga Sep 22 '21 at 00:18
  • See [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/in_operator_no_object) to clear up a common confusion about the `in` operator in JS. See [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) vs [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) for the difference between `for of` and `for in` in JS – juanpa.arrivillaga Sep 22 '21 at 00:26

1 Answers1

1

JavaScript does not have a not keyword. Instead, it has a ! for whenever you want to use not. JS's in is NOT the same as python's in. JS uses it for indexes, and if you want the character at the index, you should use of.

I have also made some minor tweaks here and there like not using var and removing the continue statements.

function removeVowels(string) {
    // Instead of using var here, use let and const.
    let newString = '';
    const vowels = ['a','e','i','o','u'];
    // Loop through every character of string
    for (const char of string) {
        // Instead of the continue that you used, you can just simply check if the vowels array includes the specific character.
        if (!vowels.includes(char.toLowerCase())) {
            // This just appends the character to the new string variable
            newString += char;
        }
    }
    return newString;
}
console.log(removeVowels('This string will not have any vowels in it.'));