I have two little projects that I've been working on.
One is to find all palindromes:
function palindrome(str) {
var replaceStrChr = str.replace(/\W/g,'').replace(/ /g,'').replace(/_/g,'').toLowerCase();
var arrayifyStr = replaceStrChr.split('').reverse();
var stringifyStr = arrayifyStr.join('');
if (replaceStrChr === stringifyStr){
return true;
} else {
return false;
}
}
And the other one is to find the longest word in a string:
function findLongestWord(str){
var arrayify = str.split(' ');
var longest = 0;
for(var x = 0; x < arrayify.length; x++){
if (arrayify[x].length > longest){
longest = arrayify[x].length;
}
}
return longest;
}
What I'm looking for is a better way to do these, shortcuts, better syntax, etc.
2 Answers 2
For the palindrome:
You can probably just use one
replace
operation, but with a more extensive regex. My regex is rusty but something like/[\W_\s]/g
could do.split
,reverse
andjoin
could possibly be just one chain.var reversedString = replaceStrChr.split('').reverse().join('');
Comparisons are essentially boolean values. You can simply do:
return replaceStrChr === stringifyStr;
For the longest word:
Use
reduce
and carry through the longest word.var longestWord = str.split(' ').reduce(function(prev, next){ return next.length > prev.length ? next : prev; });
str
doesn't tell me what the string contains. Only when I sawsplit(' ')
did I realize it was a space-separated string. Rename the variable to show its purpose.
I pretty much second everything in @Joseph the Dreamer's answer except for simplifying the palindrome.
You can simplify the regex by making it just /[\W_]/g
. So, we now can get the reduced string. We do not need to check for white spaces since those are non-word characters (\W
).
replaceStrChr = str.replace(/[\W_]/g, '');
Then there is no need to reverse the string then compare them. We can save time by checking it at the same time:
for(var i = 0, j = replaceStrChr.length; i < j;)
if(replaceStrChr[i++] !== replaceStrChr[j--]) return false;
return true;
Hope this helps!