简体   繁体   中英

To find unique characters in a string using javascript

Write a JavaScript program to find the unique characters in a string. The function uniqueCharacters must take a string as its argument and return the same after removing all the characters that appear more than once in the string. This is the main function.

The function modifyString is the sub-function. This is invoked from within the function uniqueCharacters with the same string as the argument. This function will remove all the white space characters & convert the entire string to lower case and return the same to the caller.

Note: You may verify the correctness of your function by invoking it from within console.log

console.log(uniqueCharacters("Welcome to the Javascript course"));

Where am I going wrong? My code (below) isn't working correctly. The output should be: welcomthjavsripu .

function modifyString(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
}

function uniqueCharacters(str)
{
   modifyString(str);
   var str1=str;
   var uniql= "";
   for(var x=0;x<str1.length;x++)
   {
       if(uniql.indexOf(str1.charAt(x))==-1)
       {
           if(str.charAt(x) === ' ')
           {
               continue;
           }
           uniql += str1[x];
       }
   }
   return uniql;
}
console.log(uniqueCharacters("Welcome to the Javascript course"));

I see two issues with your code:

  • First you need to replace modifyString(str) with str = modifyString(str)
  • Second you only call toLower on the first character of your string, but you expect your whole string to be lowercase. The modifyString function should simply be return str.toLowerCase();

I would use the approach of counting characters with Map and then filter them.

 function uniqueCharacters(str) { const uniqChar = new Map(); const result = [] for(const character of str) { if(uniqChar.has(character)) { uniqChar.set(character, uniqChar.get(uniqChar) + 1) } else { uniqChar.set(character,1) } } uniqChar.forEach((val,key) => { if(val === 1) result.push(key) }) return result; } console.log(uniqueCharacters("AbaacddeR"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM