gpt4 book ai didi

javascript - 如何以不区分大小写的方式删除字符串中的重复字母,以便该字母只出现一次?

转载 作者:行者123 更新时间:2023-11-29 18:44:56 25 4
gpt4 key购买 nike

我需要创建一个函数来删除重复的字母,无论它是大写还是小写。

如果我的输入字符串是 FoxfoXtAg,预期的输出将是 FoxtAg。我的输出是 FoxfXtAg,它只删除了小写字母 o

我还使用了 .toLowerCase(),它给出了预期的输出,但改变了大小写。

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"));

最佳答案

您可以使用 Array.from() 将字符串转换为数组.这使我们能够逐个字母地对其进行迭代。

要进行该迭代,最好的选择是 reduce() ,用于将数组转换为单个结果(如字符串)。

reduce() 内部将使用不区分大小写的正则表达式来确定我们是否已经“使用”了该字母。如果是新字母,我们只会将其添加到输出中。

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") );

关于javascript - 如何以不区分大小写的方式删除字符串中的重复字母,以便该字母只出现一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54539844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com