const deduplicate1 = string => { let result = Array.from(newSet(string.split(''))).join('') return result }
方法二:逐一取出字符串首元素同时过滤相同元素
1 2 3 4 5 6 7 8 9 10
const deduplicate2 = string => { let result = [] let arr = string.split('') while (arr.length) { let current = arr.shift() result.push(current) arr = arr.filter(item => item !== current) } return result.join('') }
方法三:逐一取出字符串首元素同时过滤相同元素正则版
1 2 3 4 5 6 7 8 9 10 11 12
const deduplicate3 = string => { let s = string let result = [] let current = '' while (s.length) { current = s[0] result.push(current) s = s.slice(1) s = s.replace(eval(`/${current}/g`), '') } return result.join('') }