I need to make a function that removes duplicate letters regardless of it is uppercase or lowercase.
If my input string is FoxfoXtAg, the expected output will be FoxtAg. My output is FoxfXtAg which only removes the lowercase o.
I have also used .toLowerCase(), which gives the expected output, but changes the case.
let duplicateLetter = (string) => {
//check if string only contains letters
if (!string.match(/^[a-zA-Z]+$/gi)) {
console.log('does not match')
}
//check to see if it is a string
if(typeof(string) !== 'string') {
return 'Please return a string'
}
//make string lowercase (couldn't find check for case insensitive)
string = string.toLowerCase()
//this gets rid of spaces as duplicate characters
string = string.split(' ').join('')
//creates set with only unique elements
let noDuplicates = [...new Set(string)];
return noDuplicates.join('')
}
console.log(duplicateLetter("FoxfoXtAg"));
You could transform your string into an array using Array.from(). This allows us to iterate over it letter by letter.
To do that iteration, the best option would be reduce(), which is used to convert an array into a single result (like a string).
Inside the reduce() would be case-insensitive regex to determine if we've already "used" that letter or not. We only add the letter to the output if it's new.
function removeDuplicates(str) {
let result = Array.from(str).reduce((output, letter) => {
let re = new RegExp(letter, "i"); //Create case-insensitive regex
return re.test(output) //Does our output include that letter already?
? output //Yes - don't modify the output
: output+letter //No - add it to the output
}, "");
return result;
}
console.log( removeDuplicates("HELLOworld") );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With