This is an task from codesignal.
It’s not a homework or something else, just I writed a code and now trying understand what’s wrong.
Let’s see task requirements.
Define a word as a sequence of consecutive English letters. Find the longest word from the given string.
Example.
For text = "Ready, steady, go!", the output should be
solution(text) = "steady".
Well, now I’m sharing my code.
function solution(text) {
let words = text.match(/\w+/g);
let ml = Math.max(...words.map(el=>el.length))
for(let i = 0; i < words.length; i++){
if(words[i].length == ml){
return words[i]
}
}
}
It’s passing all tests, except of one hide test. Now I opened that hide test it looks like this text: "ab-CDE-fg_hi". Expected output of this test is "CDE" .
Now I’m trying understand what’s the problem and why it’s not passing this test, can someone please explain me.
I’m newbie so please be more polite)
>Solution :
/\w+/ also includes an underscore, try to make the regex more precise, for example /[A-Za-z0-9]+/:
function solution(text) {
let words = text.match(/[A-Za-z0-9]+/g);
let ml = Math.max(...words.map(el=>el.length))
for(let i = 0; i < words.length; i++){
if(words[i].length == ml){
return words[i]
}
}
}
console.log(solution("ab-CDE-fg_hi"));
You could also iterate the words immediately and find your max sooner:
function solution(text) {
let max = '';
for(const word of text.match(/[A-Za-z0-9]+/g)){
if(max.length < word.length){
max = word;
}
}
return max;
}
console.log(solution("ab-CDE-fg_hi"));