How to write a function that takes a string and return a new string?

Hello there,
can anyone help on how to to write a function that takes a string and return a new string with all vowels removed.
E.g, if the String is ‘what will you do tomorrow’.

Is this a class assignment? What language are you using?

Hi there, it is Javascript.
I am just trying to practice on my own.
thanks

So you want to start with a signature line and body…

const foo = x => {

}

We will want to verify that x is a string object.

  if (typeof x !== 'string') {
    throw Error('Value error')
  }

Next we will define a vowel array…

  const y = 'aeiouAEIOU'.split('')

Now the tricky part, iterating the vowels and removing them from x. There are a number ways we can do this. We’ll use a brute force method…

  y.forEach(c => {
    while (x.includes(c)) {
      x = x.replace(c, '')
    }
  })
  return x

Now you try… Can you write a naive algorithm that illustrates the finer details?

Thanks for your reply. But the explanation is too complex for me to understand. It is above my understanding at the moment. :grinning:

1 Like

That was on purpose. Think this one through. Show us your steps.

1 Like

To be honest , i dont have any steps. i am just stuck on writing the first line.
i do know that i need to create the vowel array e.g

   const vowels = ['a', 'e','i','o','u']

I also know i need to write the string.
e.g

     let strin = 'what will you do tomorrow'

Then create empty array where the new elements will go

let newArr = []

. Then i need to use a nested for loop to iterate the strin and vowels and use the if conditonal statement to compare each index and use .push() to put the new element into the new array.
e.g

for (let i = 0; i < strin.length; i++) {
  for (let j = 0; j < vowels.length; j++) {
if(strin !== vowels[j]) {
newArr.push(strin[])

}
}


I dont know how strings can come into a function and output string. 
 Also all i wrote above are process that i have read
 but dont know how its all adds up.

For that we have the Array.join() method.

return newArr.join('')

The method takes an array as the context object (in front of the dot) and a separator string for an argument. In this case there is no space between characters so we pass in an empty string.

Given this array,

newArr = [ 'w',
  'h',
  't',
  ' ',
  'w',
  'l',
  'l',
  ' ',
  'y',
  ' ',
  'd',
  ' ',
  't',
  'm',
  'r',
  'r',
  'w' ]

the above return will be,

wht wll y d tmrrw

Your strin should be a subscript, strin[i] which is also what you would push to the array.

You are on the right track as far as writing a naive approach (nested loops). The method uses indices i, and j to access values in the string and in the array. However, we can improve on that since there is no mutation of either object. Are you familiar with the loop operator, of?

for (let i of strin) {
    for (let j of vowels) {
        // code
    }
}

The of operator lets as access the values directly without using their index. The sequence is still traversed in its original order so we do access every value in both objects.

Keep in mind, also, that we want the function to work on both lower and upper letter cases.

Tip

An easy way to create an array of characters is to write the string, then split it. Saves on typing and avoids errors.

const vowels ='aeiouAEIOU'.split('');  // empty string separator

Please keep us posted on your progress. Do not hesitate to look up documentation on MDN of any keywords you are not fully familiar with. This is how the real learning is done. We don’t have to memorize anything, just learn about its usage and put in the practice. It will all eventually stick and make sense. Then we can implement it in our designs.

`let strin = 'what will you do tomorrow'`

Thanks for the expalantion.
But how do i

  1. put the above string into array?
    2)put the above string into a function?

thanks

We don’t have to put the string into an array. It is already iterable. Technically, we don’t need a vowels array, either, just a string.

The string comes into the function via the parameter which is the local name we give to the argument.

As suggested above, start with the signature and body when writing the function.

const dropVowels = str => {

}

str is the local name we give to the string argument. For now we can forego error checking and let JS report any errors thrown.

Inside the function we can declare our vowel string…

const vowels = 'aeiouAEIOU';

Next, declare the return array,

const noVowels = []

Now into the loops…

for (let x of str) {
  for (let y of vowels) {
    if (x !== y) {
      noVowels.push(x)
    }
  }
}

And now we’re ready for the return…

  return noVowels.join('')

Now we can test your function.

console.log(dropVowels('what will you do tomorrow'))
           // function call with string argument

We write the call directly into console.log() if we only want to print it, not save it, otherwise we assign the return value to a variable.


The approach I used earlier (note that I fixed some omissions) takes into account some methods that you may not yet be familiar with. They are called, iterators, and bring a lot of horsepower to the table.

When you get to the unit that covers these, (Array.forEach(), String.includes()) come back to this project and give it another go.

We also used the brute force attack on the actual string using the String.replace() method which should come up in the unit on string methods. Since you are using for loops, perhaps you are also familiar with while? If not, expect it to come up very soon in your studies.

At some point you will reach the unit on Error Handling, by which time you will gain an understanding of the validation used. To recap, here is my function, in complete form…

const dropVowels = x => {
  if (typeof x !== 'string') {
     throw Error('Value error')
  }
  const y = 'aeiouAEIOU'.split('');
  y.forEach(c => {
    while (x.includes(c)) {
      x = x.replace(c, '')
    }
  })
  return x
}
console.log(dropVowels('what will you do tomorrow'))
wht wll y d tmrrw

We iterate the vowels array with forEach and iterate the string with includes. We need to put the latter in a while loop since String.replace() only replaces one instance at a time. Without the loop we would only remove one o from the input string. The loop ensures we get all that are present.

This approach is quite better and not too advance for me at this stage. And i understand the way you break it into pieces.
1)Expressing a function with string as parameter
2)declaring a variable string vowels
3)creating new empty array list to take in new elements
4)using the for loop and of operator(first time of hearing it)
5)pushing the new element into empty array using .push()
6)using the return function key word and calling the function.

I can also see in the below approach that one can write same
code using multiple approach as long as the concept is understood.

I have a Long Way to go :grinning:

Thank you for your time . I appreciate

1 Like

and thereby outlining our steps. This approach is more important to know and utilize than my fancy approach. We never want to under rate that importance. I start every project with naive code, and then refine and refactor, later. Form this habit and soon you will have an idea of the steps right in your head when facing a new problem.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.