Create a function that will return the number of words in a text.
We are going to write a function called
countWords that will accept a string,
text, as an argument.
The goal of the function is to return how many words are in that string of text.
The function should ignore any non-alphanumeric characters as part of the word count. Words containing hyphens should also be counted as one word.
The first thing we do is create a variable called
removeChar. In this variable, we remove any excess whitespace within the text and punctuation. For this, we use a combination of regular expression and the
let removeChar = text.replace(/[^A-Za-z]\s+/g, " ");
The regular expression inside the
/[^A-Za-z]\s+/g, takes all non-alphanumeric characters and replaces them with single spaces. In detail:
/[regular expression]/g: Instead of stopping at the first match, the
g looks at all the possible matches in the text.
[^A-Za-z]: Matches any character that isn’t A-Z and a-z.
\s: Matches whitespace characters.
+: Matches 1 or more of the preceding token (in this case above, the whitespace).
With all those characters removed, it’ll be easier to count the number of words in
I previously wrote about some common coding algorithms that you’ll run into on your job search. The article was received fairly well so I thought I’d do a couple more to help in your journey to becoming more familiar with algorithms.
Today I am going to be sharing two common coding algorithms as well as their solutions and some links to resources that will help you expand your knowledge of algorithms.
Static code analysis is a method of debugging by examining source code before a program is run. It's done by analyzing a set of code against a set (or multiple sets) of coding rules. Static code analysis and static analysis are often used interchangeably, along with source code analysis.