Your regular expression searches for pairs of duplicate characters and only deletes the first. Therefore, the last duplicate will not be deleted.
To solve this problem, you should remove all duplicates at the same time, but I don’t think you can do it with one replace .
Instead, I would build a map that counts the occurrences of each character, and then iterates over the line again, clicking on the characters that appear only once for a new line:
function onlyUnique(str) { var map = Object.create(null); for(var i=0; i<str.length; ++i) map[str[i]] = (map[str[i]] || 0) + 1; var chars = []; for(var i=0; i<str.length; ++i) if(map[str[i]] === 1) chars.push(str[i]); return chars.join(''); }
Unlike indexOf , hash map searches are on average constant. So the call cost with character string n will be n .
source share