ITried
ITried

Reputation: 41

how to replace multiple word to a single word in javascript?

Basically I have a string of:

var str = "aaaa aaa aaaaaa safsd a a a aaaa";

Note: a could be x times,

I need to replace all as connected together to a single a, for Example replace aaaa to a and the output that I need from above str should be something like:

Output: a a a safsd a a a a

Upvotes: 2

Views: 225

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521389

Here is a slightly modified answer to what was posted earlier:

var str = "aaaa aaa aaaaaa safsd a a a aaaa";
str = str.replace(/a{2,}/g, "a");
console.log(str);

The difference here is that we only do a replacement for two or more a's. A single a does not need to be involved.

Upvotes: -1

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

You can use string.replace(regexp, newString) and use /a+/g to match one or more a's.

var str = "aaaa aaa aaaaaa safsd a a a aaaa";

str = str.replace(/a+/g, "a");

console.log(str)

Upvotes: 4

Related Questions