Just the Consonants

While this question might be mistakenly asked in a "History of JavaScript" class, the place I found this question makes it obvious that the question expects a modern answer. This doesn't prevent it being asked in a history class though.

Question:

Write a function to sort this string: The teacher's name is Robert so that the function will return this string(the consonants): ThtchrsnmsRbrt.

The obvious way to solve this is to use a regular expression but it can be solved without one.

Historical Answer:

function consonantsOnly(str) {
var consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
var result = "";
for (var i=0; i < str.length; i++) {
if (vowels.indexOf(str.charAt(i)) != -1) result += currChar;
}
return result;
}

This function does things the hard way by using a loop to extract each character individually from the string and then test if that character is in the consonants string. If it is then it gets added to the result string. This code is not only inefficient for answering the question, it is also easy to get wrong as you need to include both the lower and upper case consonants in the string to compare against or you will not output all of the required characters. If you were to test for vowels instead and reverse the test then you wouldn't be stripping out the spaces or other non-alphabetic characters.

If this question were given to a class where regular expressions had not yet been taught then this would probably be the answer the teacher would expect seeing as how the question has been asked before teaching how to solve it properly.

JavaScript Answer:

consonantsOnly - function(str) {
return str.replace(/[^bcdfghjklmnpqrstvwxyz]/gi, '');
}

This solution makes it obvious that this question is actually intending to test your knowledge of how to write regular expressions since this one line replace statement using a regular expression easily produces the correct result.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate