When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Stump the SQL Guru!
XML Info
Author an Article
ASP ASP.NET ASP FAQs Message Board Feedback

The 4 Guys Present: ASPFAQs.com

Jump to a FAQ
Enter FAQ #:
..or see our 10 Most Viewed FAQs.

4GuysFromRolla.com : ASP FAQS : Strings


How can I remove multiple spaces between words in a string? That is, if I have: Hi    there how can I get: Hi there?

[Print this FAQ]

Answer: There are a number of techniques that can be used to remove extraneous spaces from a string. VBScript includes a couple of functions to help remove leading and/or trailing spaces from a string. LTrim removes leading spaces, RTrim removes trailing spaces, and Trim removes both leading and trailing spaces. For example:

Dim str
str = " Leading and trailing spaces... "

str = Trim(str)

'At this point str = "Leading and trailing spaces..."

While these trimming functions are nice, they don't remove extraneous spaces from between words in the string. For example, if we had the string:

This    is     a  test.

We might want to remove those extra between-word spaces, converting the string to:

This is a test

Unfortunately there is no built-in VBScript function that will do this for us. However, it is not too difficult to write our own code to handle this. There are two simple methods for doing this, the first uses the VBScript Replace function to continually replace all instances of two consecutive spaces with one space until there are no instances of two consecutive spaces in the string.

'Start by trimming leading/trailing spaces
str = Trim(str)

'Now, while we have 2 consecutive spaces, replace them
'with a single space...
Do While InStr(1, str, "  ")
  str = Replace(str, "  ", " ")

Be sure to view the live demo of this function!

Another way to accomplish the same feat is to use regular expressions. (For information on regular expressions be sure to visit the Regular Expressions Article Index.) With regular expressions we can say, "Find occurrences of two of more whitespace characters (tabs, spaces, etc.) and replace it with a single space." The regular expression for finding a space character is \s. To specify that we want to match two or more occurrences of the space character we use: \s{2,}. Here is the source code:

Dim regEx
Set regEx = New RegExp
regEx.Global = true
regEx.IgnoreCase = True

regEx.Pattern = "\s{2,}"

str = Trim(regEx.Replace(str, " "))

Be sure to view the live demo of this function!

Either of these two methods can be used to remove extraneous spaces from between the words of a string.

Alert ASPFAQs.com reader Eveline S. wrote in...

Thanks for sharing the code alternatives. They are very useful for the "ASP newbie", like me, and very much appreciated.

I do have one question, though. I tested the code on the pages you provided:
" I  think    this is   great  !"
"I think this is great !"

My question: The words are correctly separated by a space, but how do you make sure there is no space between a word and the following punctuation (i.e., "great !" versus "great!")?

The solution is to use a second regular expression search and replace after you've used the first one. This second one replaces any space followed by a punctuation mark with just the punctuation mark.

To accomplish this, the regular expression to use is:
which looks for a space (\s) followed by any punctuation mark. To replace the match with the proper punctuation mark, you must use a back-reference - $1:

regEx.Pattern = "\s(\!|\.|\?|\;|\,|\:)"

str = regEx.Replace(str, "$1")

This would be integrated into our earlier example, immediately following the first regular expression replace. Therefore, our complete code would look like:

  str = " This is a , test fool ! "

'Remove extraneous spaces
  Dim regEx, Match, Matches
  Set regEx = New RegExp
  regEx.Global = true
  regEx.IgnoreCase = True
  regEx.Pattern = "\s{2,}"

  str = Trim(regEx.Replace(str, " "))

'Remove the space between the end of a word and
'a punctuation mark
  regEx.Pattern = "\s(\!|\.|\?|\;|\,|\:)"
  str = regEx.Replace(str, "$1")

Neat, eh? For an example of using the back-reference ($1) check out Common Applications of Regular Expressions.
Happy Programming!

FAQ posted by Scott Mitchell at 3/31/2001 5:02:55 PM to the Strings category. This FAQ has been viewed 129,557 times.

Do you have a FAQ you'd like to suggest? Suggestions? Comments? If so, send it in! Also, if you'd like to be a FAQ Admin (creating/editing FAQs), let me know! If you are looking for other FAQs, be sure to check out the 4Guys FAQ and Commonly Asked Messageboard Questions!

Most Viewed FAQs:

1.) How can I format numbers and date/times using ASP.NET? For example, I want to format a number as a currency. (761643 views)
2.) I am using Access and getting a 80004005 error (or a [Microsoft][ODBC Microsoft Access Driver] The Microsoft Jet database engine cannot open the file '(unknown)' error) when trying to open a connection! How can I fix this problem? (207777 views)
3.) How can I convert a Recordset into an array? Also, how can I convert an array into a Recordset? (202549 views)
4.) How can I quickly sort a VBScript array? (196039 views)
5.) How can I find out if a record already exists in a database? If it doesn't, I want to add it. (156019 views)
6.) How do I display data on a web page using arrays instead of Do...While...MoveNext...???... (152331 views)
7.) When I get a list of all files in a directory via the FileSystemObject, they aren't ordered in any reasonable way. How can I sort the files by name? Or by size? Or by date created? Or... (140381 views)
8.) For session variables to work, must the Web visitor have cookies enabled? (110162 views)
9.) Can I send emails without using CDONTS? (107083 views)
10.) How can I take the result of a SELECT...MULTIPLE or a group of same-named checkboxes and turn it into a query? That is, if the user selects 3 answers, how can I construct a query that looks for all 3? (106308 views)
Last computed at 9/17/2007 3:22:00 AM

ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article