coffeeak
coffeeak

Reputation: 3130

How to replace any number of   in string jquery

I would like to replace a number of " " inside an html string to one space only. But, it will replace each and every single " " to a space, resulting in many spaces. For example,

htmlValue.replace(/ /gi, " ");//"  " becomes "  ". (2spaces) but I want only 1 space

Upvotes: 2

Views: 690

Answers (2)

Vishal Surjuse
Vishal Surjuse

Reputation: 170

Try this.

htmlValue.replace(new RegExp(' ', 'g'), ' ');

Upvotes: 2

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10476

You can try this:

/( )+/gm

and replace by single " "

Explanation

Sample Code:

const regex = /( )+/gm;
    const str = `   sfdasdf   `;
    const subst = ` `;
    const result = str.replace(regex, subst);
console.log(result);

Upvotes: 2

Related Questions