javascript - Regular expression that remove second occurrence of a character in a string -
i'm trying write javascript function removes second occurrence of character using regular expression. here function
var removesecondoccurrence = function(string) { return string.replace(/(.*)\1/gi, ''); }
it's removing consecutive occurrence. i'd remove non consecutive one. example papirana should become pairn.
please help
a non-regexp solution:
"papirana".split("").filter(function(x, n, self) { return self.indexof(x) == n }).join("")
regexp code complicated, because js doesn't support lookbehinds:
str = "papirana"; re = /(.)(.*?)\1/; while(str.match(re)) str = str.replace(re, "$1$2")
or variation of first method:
"papirana".replace(/./g, function(a, n, str) { return str.indexof(a) == n ? : "" })
Comments
Post a Comment