javascript - JS - Comparing length of words in string, ignoring non-letter chars -
this coderbyte js challenge. goal write function takes in string , returns longest word in string. if 2 words same size first word returned. input never empty. example, input = "fun&!! time" result in: output = "time"
this question has been asked before, although original question involved using variety of string methods , regexp. js (and programming noob) , find approach non-intuitive, , trying assess whether alternate method feasible approach problem:
function longestword(sen) { var count = ''; var max = 0; //loops thru string & tallies letters in sequences (i = 0; < sen.length; i++) { if ((sen.charat(i) >= 'a' && sen.charat(i) <= 'z') || (sen.charat(i) >= 'a' && sen.charat(i) <= 'z')) { count += sen.charat(i); //conditional tracks longest letter string date if (count.length > max){ max = count; } } //resets count if encounters non letter value in string else { count = ''; } } return max; }
this seems work in recognizes whether or not first char letter or not , logs var count, not iterating through array i'd expected.
is valid approach? or need learn more string methods , regexp before come this? thanks!
the problem occurs due comparison of integer count.length
string max
this can solved initializing max empty string max = ''
, compare count.length
max.length
here working jsfiddle
Comments
Post a Comment