Steven Bell
Steven Bell

Reputation: 25

How to remove repetitive chars in javascript

I have a file that contains words with repetitive chars, like:

In Javascript(used on nodejs), how do i remove that extra chars so i get body, user etc.?

Upvotes: 1

Views: 105

Answers (3)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

Simple regex is good for such thing.

"boooody".replace(/(\w)\1+/g, "$1");
// "body"

Upvotes: 1

Boris Guéry
Boris Guéry

Reputation: 47585

var words = [
    'boooody',
    'Steveeen',
    'uuuuuuser',
    'etccccc'
];

for (var i = 0, l = words.length; i < l; ++i) {
    var word = words[i].replace(/[^\w\s]|(.)(?=\1)/gi, ""); 
}

Runnable example on JSFiddle ​

Upvotes: 0

user1726343
user1726343

Reputation:

Try this:

str.replace(/(.)\1{1,}/g, "$1");

Upvotes: 3

Related Questions