0

I'm trying to write a regexp that selects whitespace before or after any character( letters, symbols, or numbers ), but not in-between words composed of the characters.

For example, in ' abc', the spaces before would match; but, in 'words words words' none of the whitespace in-between would be selected.

So in ' hello world to everyone ', only the leading and trailing whitespace would be selected.

Bonus: if there's a way to separately, in a second regexp, select the white-space in-between, that would help alot.

What i'm trying to do is, in javascript, minimise the whitespace in a sentence so that leading and trailing whitespace is gone and the white-space in-between words is shrunk to 1 space.

Eris
  • 7,378
  • 1
  • 30
  • 45
wordSmith
  • 2,993
  • 8
  • 29
  • 50

3 Answers3

3

Reference Link

var string = "    hello world     to       everyone. ";
string = string.trim().replace(/\s+/g, " ");
alert(string);

JS Fiddle

Community
  • 1
  • 1
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
  • 1
    Thank you for solving my problem and not just giving me the easiest solution. I didn't know there was a trim method. I'll look into that some more. – wordSmith Dec 25 '14 at 05:51
2

Are you trying to make multi-space to be one-space ? Just do :

var text="hello world  to    everyone";
text=text.trim().replace(/\s+/g," ");

document.write(text); // It will print 'hello world everyone'
Eris
  • 7,378
  • 1
  • 30
  • 45
Mike
  • 1,231
  • 12
  • 17
0

Through regex and regex only

You could do this through regex without using any js inbuilt functions like trim()

> var s = '    hello    world   to    everyone   '
> s.replace(/^\s+|\s+$|\s*(\s)/g, "$1")
'hello world to everyone'

DEMO

Explanation:

  • ^\s+ Matches the leading one or more spaces.
  • | OR
  • \s+$ Matches the trailing spaces.
  • | OR
  • \s*(\s) From the remaining string, this regex would match zero or more spaces and captures the last space. So the captured group that is, group index 1 a single space.
  • Replacing all the matched spaces with the space present inside the group index 1 will give you the desired output.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274