A new beginning ( JavaScript methods included)

I’m starting a blog to chronicle both the transition I’m making in my career (from musician/educator to web developer) and the new things I’m learning. So, I thought I’d start by writing about a coding challenge I came across and how I solved it.

In this post, I’m going to show how to string and array methods (and one property) to take a string, manipulate it, and return a modified string.

Here are the methods/tools I used to complete the challenge.

  • String — .split(), .toUpperCase(), .replace()
  • Array — .forEach(), .push()
  • Other — if/else, .length, regex (just a touch)

Today’s challenge — Take a given sentence and turn all the words that are less than three letters into all caps, remove all the vowels from the rest of the words. Return the modified sentence. We need to make sure our solution can solve these two cases. For the record, this challenge came from codewars.

The quick brown fox stole my lunch!
The quick brown fox stole my lunch, and ate it!

The first thing I did to solve this challenge was to break it into parts. As I saw it, the steps I needed were to:

  • Break the sentence (a string) into individual words (an array)
  • Sort the words according to size
  • Modify each word
  • Take the array of modified words and combine them back into a sentence

The function

Let’s start by defining a function. It’ll take one argument and return the modified sentence.

var textChange = function(text) {
//do things
}

Task 1 — Break ups are easy.

We have a whole string. In this case a sentence. We need to break it into pieces The string split() method is perfect for this. It takes any string and breaks it into pieces that will be held in an array. We’ll use text.split(‘ ‘) to make sure the text is broken into individual words.

var textChange = function(text) {
var wordArr = text.split(‘ ‘);
}

Task 2 — Sorting and sifting.

Now that we’ve got an array, we’ve got to iterate (loop) through it somehow. There are two main ways to do this. One is the venerable for loop. The other is to use an array method. I decided I wanted to practice a little functional programming here, so I chose the .forEach() array method. This method goes through “each” item in the array and let’s you do things to it.* The method takes a callback as an argument to perform the operation. That means inside the callback we can use an if…else statement (or a ternary operator) to sort the words. Plus, strings have a .length property which means we have a simple way to check how long each word is. Perfect. Now we have…

var textChange = function(text) {
var wordArr = text.split(‘ ‘);
wordArr.forEach(function(word){
if (word.length <= 3) {
//do something…
}
else {
//do a different thing…
};
});
};

Task 3 — Sometimes change is easy too.

Back to our challenge, we want to turn all the short words (<= 3 letters) into all caps. This is super easy with the .toUpperCase() string method. Getting rid of the vowels is slightly trickier. The .replace() method with a little regex will help us here. We’re going to use .replace(/[aeiou]/ig, ‘’) to look for the all the vowels and remove them (the ‘’ at the end). In this case Medium’s being a little annoying. The ‘’ is really two single quotation marks…

var textChange = function(text) {
var wordArr = text.split(‘ ‘);
wordArr.forEach(function(word){
if (word.length <= 3) {
word.toUpperCase();
}
else {
word.replace(/[aeiou]/ig, ‘’);
};
});
};

At this point though we have a problem. We’ve sorted the words, and we can manipulate them, but we have no way to store them.** So let’s define a new array that we can push to.

var textChange = function(text) {
var wordArr = text.split(‘ ‘);
var changedTextArr = [];
  wordArr.forEach(function(word){
if (word.length <= 3) {
changedTextArr.push(word.toUpperCase());
}
else {
changedTextArr.push(word.replace(/[aeiou]/ig, ‘’));
};
});
};

Task 4 — Time to get back together.

Now we need to recombine our changedTextArr so that it gives us back our sentence when we return the function. We can do this with the .join() array method which is the opposite of .split(). It takes our array and “joins” all the parts back together. Then we get rid of all the commas with our old friend the .replace() method this time just taking out commas. We’ll use a new variable that we can modify and then return.

var textChange = function(text) {
var wordArr = text.split(‘ ‘);
var changedTextArr = [];
var newText;

wordArr.forEach(function(word){
if (word.length <= 3) {
changedTextArr.push(word.toUpperCase());
}
else {
changedTextArr.push(word.replace(/[aeiou]/ig, ‘’));
};
});
  newText = changedSentenceArr.join().replace(/,/ig, ‘ ‘);
return newText;
};

Task 5 — Celebrate?

We did it! Sort of? You’re about to argue with me… I can tell… You’re going to say, “Yeah fine, but what about sentences that have commas in them (like this one)?” You’re right. Our regex isn’t refined enough. It strips out the commas ok, but it gets rid of all of them. Including the ones that are supposed to be there. The solution is to add a \b to our regex. I found this in Eloquent Javascript which says “The code \b matches a ‘word boundary’, which can be punctuation, white-space, or the start or end of the string.” Exactly what we need. So, the full answer is now…

var textChange = function(text) {
var wordArr = text.split(‘ ‘);
var changedTextArr = [];
var newText;

wordArr.forEach(function(word){
if (word.length <= 3) {
changedTextArr.push(word.toUpperCase());
}
else {
changedTextArr.push(word.replace(/[aeiou]/ig, ‘’));
};
});
  newText = changedSentenceArr.join().replace(/,\b/ig, ‘ ‘);
return newText;
};

Task 5a — Celebrate!

That’s it for now! This could/should be refactored, again, my gut tells me that .map() would be useful here, a ternary operator would be easy to implement, and we could get fancy with ES6 syntax. But my feeling is it’s better to get something going and refine it later than worry about being clever and never getting anything done.

I hope you’ll let me know what you think about this approach.


NB — .map() does something very similar and might be better in this case. As soon as I figure out a solution with it, I’ll edit my answer.

** Again, this is probably where .map() would help since it returns a new array.

Like what you read? Give Adam Berkowitz a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.