Improving your whitespace removal
In order to remove spaces, you are calling string.replace
once for every occurrence of " " (space) in each string. An easier way to remove whitespace in a string is to use a regular expression object with a global modifier, which will replace all matching characters in the string. Then, you can get rid of your while-loops, and your code becomes slightly easier to read.
function findAnagram (firstWord, secondWord) {
// "/ /g" is a regular expression object that finds all spaces in a string.
secondWord = secondWord.replace(/ /g, "");
firstWord = firstWord.replace(/ /g, "");
...
You can also use the /\s/g
regular expression object to replace all whitespace including tabs, newlines, etc.
Improving your algorithm
Your version (with the fixes above) works fine, but has a complexity O(n^2).
One very simple, readable way to see if two strings are anagrams is to remove whitespace, sort the letters, and then compare the sorted strings. This brings our complexity down to (depending on implementation) O(nlog(n)). Example:
// Returns the given string with whitespace removed.
function removeWhitespace(str) {
return str.replace(/\s/g, '');
}
// Returns the given string sorted by character value.
function sortString(str) {
return str.split('').sort().join('');
}
// Returns true if the given ASCII strings are anagrams of each other.
function isAnagram(str1, str2) {
const trimmedStr1 = removeWhitespace(str1);
const trimmedStr2 = removeWhitespace(str2);
// If the strings have different lengths, there is no way for them to be anagrams.
if (trimmedStr1.length != trimmedStr2.length) {
return false;
}
// Characters should have the same capitalization before sorting.
const sortedStr1 = sortString(trimmedStr1.toUpperCase());
const sortedStr2 = sortString(trimmedStr2.toUpperCase());
return sortedStr1 === sortedStr2;
}
For more examples of how to solve this problem, see this post.
Of course, if you want to compare Unicode anagrams, that's a whole different story.