简体   繁体   中英

Javascript Regex - Remove single spaces NOT double spaces

I need to remove singles spaces from a string but not double spaces.

Using regex I've tried this, however it is invalid and I'm not sure how to fix it:

\s+{1,1}

This is what I want to achieve:

Raw string:

"Okay,  let ’s  get  star ted,  Bret t "

After regex replace (keeping the double spacing):

"Okay,  let’s  get  started,  Brett"

Since JavaScript doesn't support lookbehinds, I believe you have to can resort to a callback function:

str = str.replace(/\s+/g, function(m) {
    return m.length === 1 ? '' : m;
});

You could use this:

"Okay,  let ’s  get  star ted,  Bret t ".replace(/(\S)\s(\S)/g, '$1$2')

But this will not remove the space at the end of string, you could trim it by:

"Okay,  let ’s  get  star ted,  Bret t ".replace(/(\S)\s(\S)|\s$/g, '$1$2')

Based on expression greediness this is a viable solution:

"Okay,  let ’s  get  star ted,  Bret t ".replace(/(\s{2,})|\s/g, '$1')

It matches two or more spaces if possible, for which the replacement is $1 , effectively falling back to replacing a single space with nothing.

/([^\s]\s{1}[^\s])|\s$/g

will solve your problem

\\s is for one space

^\\s is for NOT space

{1} is a quatifier which tells the number to be one

http://regex101.com/r/uO3iJ4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM