I'm working through some beginner Coderbyte problems and I've come across an interesting dilemma. Here's the problem:
"Using the JavaScript language, have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty."
Here's my code:
function LongestWord(sen) {
var myArray = sen.split(" ");
var lengthOfSubstring = 0;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].length > lengthOfSubstring) {
lengthOfSubstring = myArray[i].length;
sen = myArray[i];
}
}
return sen;
}
console.log(LongestWord("Argument goes here"));
My code passes every test unless the argument contains punctuation. Is there anyway to remove or ignore it? Every search brings up regex and very intimidating syntax haha
EDIT: used the match() method on the sen parameter courtesy of @Markus
function LongestWord(sen) {
var myArray = sen.match(/[a-z]+/gi);
var lengthOfSubstring = 0;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].length > lengthOfSubstring) {
lengthOfSubstring = myArray[i].length;
sen = myArray[i];
}
}
return sen;
}
console.log(LongestWord("Argument goes here"));
Without regex:
function LongestWord(sen) {
var wordStart = -1;
var bestWord = null;
var bestLength = 0;
for (var i = 0; i < sen.length; i++) {
var ch = sen[i];
if ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z')
{
if (wordStart === -1)
{
wordStart = i;
}
}
else
{
if (wordStart !== -1)
{
var word = sen.substring(wordStart, i);
if (word.length > bestLength)
{
bestLength = word.length;
bestWord = word;
}
wordStart = -1;
}
}
}
if (wordStart !== -1)
{
var word = sen.substring(wordStart);
if (word.length > bestLength)
{
bestLength = word.length;
bestWord = word;
}
wordStart = -1;
}
return bestWord;
}
With regex:
function LongestWord(sen) {
var bestWord = null;
var bestLength = 0;
var matches = sen.match(/[a-z]+/gi);
for (var i = 0; i < matches.length; i++)
var word = matches[i];
if (word.Length > bestLength)
{
bestLength = word.Length;
bestWord = word;
}
}
return bestWord;
}