2

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"

4 Answers 4

3

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for callback solution, i think you missed the g modifier :)
Indeed I did. Thanks!
2

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')

2 Comments

I just wanted to add that :D
Alternately, check that a space is either the first character, or preceded by a non-whitespace, and isn't followed by a space. " Okay, let ’s get star ted, Bret t ".replace(/(^|\S)\s(?!\s)/g,'$1');
1

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.

1 Comment

That's cool too. You don't even need the second capture group. \s{2} might have to be changed to \s{2,} if the OP truly wants to replace single spaces only.
0
/([^\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

3 Comments

[^\s] is also \S, and with that replacement it's basically the first version of xdazz's answer.
ohh i thought this is just one way of saying it. People are there who dont know everything.
What I meant to say is that this has the problem of not removing space from the end of a string :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.