As was pointed out by janospointed out by janos, non-Latin characters will be removed by your replace
-call. Even English words with hyphens or apostrophes will be mangled. This may be completely intentional; depends on what you consider "a word" and what kind of input you expect.
Still, might be simpler to only split the string. For instance:
function longestWord(string) {
return string.split(/[\s\d.,!?"_\/`]+/).reduce(function (longestSoFar, currentWord) {
return currentWord.length > longestSoFar.length ? currentWord : longestSoFar;
});
}
document.write(longestWord("The apostrophe's a tricky thing."));
document.write("<br>");
document.write(longestWord("But so is a naïve regex!"));
This is of course using konijn's reduce
solutionusing konijn's reduce
solution.
The above completely avoids replace
letting split
remove things we don't want. The regex will split on whitespace, digits, and different kinds of punctuation, which keeps words like "coöperation" and hyphenations intact.
But it's certainly not without fault; regexes are tricky. There are certainly things that the code above doesn't handle well. Again, it all comes down to what you consider to be a "word" in your context, and what sort of input you expect.
As a sidenote: Your current replace
-regex could be written as /[a-z\s]/i
- the i
modifier flag mean "case-insensitive. No major difference, just an FYI.