{"id":67403,"date":"2006-05-03T21:09:00","date_gmt":"2006-05-03T21:09:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2006\/05\/03\/how-can-i-remove-blank-spaces-before-and-after-a-string-value\/"},"modified":"2006-05-03T21:09:00","modified_gmt":"2006-05-03T21:09:00","slug":"how-can-i-remove-blank-spaces-before-and-after-a-string-value","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-remove-blank-spaces-before-and-after-a-string-value\/","title":{"rendered":"How Can I Remove Blank Spaces Before and After a String Value?"},"content":{"rendered":"<p><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" border=\"0\" alt=\"Hey, Scripting Guy! Question\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" height=\"34\"> \n<P>Hey, Scripting Guy! We have a custom in-house application that writes data to a log file. The problem is that the data often has a bunch of blank spaces before and after it. How can I remove all the blank spaces that come before and after my data?<BR><BR>&#8212; KS<\/P><IMG border=\"0\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" height=\"5\"><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" border=\"0\" alt=\"Hey, Scripting Guy! Answer\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" height=\"34\"><A href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><IMG class=\"farGraphic\" title=\"Script Center\" border=\"0\" alt=\"Script Center\" align=\"right\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" height=\"288\"><\/A> \n<P>Hey, KS. You might find this hard to believe, but the Scripting Guy who writes this column occasionally has problems fitting into the modern world. For example, everyone in the world has a cell phone \u2026 everyone except you-know-who. Everyone in the world takes one look at a high-definition TV set and immediately plops down $5,000 to buy one \u2026 well, <I>almost<\/I> everyone. Everyone in the world has seen at least <I>one<\/I> episode of <I>The Sporanos<\/I>, <I>Lost<\/I>, or <I>Survivor<\/I>, right? Um, next question please. You get the idea: the poor guy is so stuck in the past that he even wears his baseball hat forwards instead of backwards!<\/P>\n<P>That\u2019s a good idea: the next time a traveling freak show comes to Redmond we\u2019ll give them a call and let them know about this guy.<\/P>\n<P>Needless to say, it\u2019s easy to make fun of this poor little guy (as well as wonder how someone who doesn\u2019t have a GPS navigation system manages to get through the day). But now thanks to your question, KS, this out-of-place Scripting Guy suddenly has a purpose in life. As it turns out, hundreds of years ago, back when dinosaurs ruled the earth and phones all had cords, this Scripting Guy was introduced to computers the hard way: by having to learn dBase III. (Yes, we know. But people were cruel back in those days.) And, for some reason, a common problem with the dBase III applications he had to deal with was this: invariably data would end up looking like your log file (for illustration purposes, pretend the asterisk marks the end of the data):<\/P><PRE class=\"codeSample\">Ken Myer          *\n                    Pilar Ackerman     *\n     Gail Erickson     *\n<\/PRE>\n<TABLE id=\"ELD\" class=\"dataTable\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD>\n<P><B>Note<\/B>. <I>Why<\/I> did the data invariably look like this? Who knows? Back then data with extraneous blank spaces was simply accepted as being the way of the universe; instead, the big debate was whether the sun revolved around the earth or vice-versa.<\/P>\n<P>A question our Scripting Guy has decided to reserve judgment on, at least for the time being.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>The important point is that, back in the good old days, our Scripting Guy actually served a useful purpose: he knew how to write code that could remove extraneous spaces from the beginning and the end of a string. And now, for one brief moment at least, his life once more has meaning. Here\u2019s a script that will open a text file, remove excess blank spaces from the beginning and end of each line, and then save the modified lines back to the file:<\/P><PRE class=\"codeSample\">Const ForReading = 1\nConst ForWriting = 2<\/p>\n<p>Set objFSO = CreateObject(&#8220;Scripting.FileSystemObject&#8221;)\nSet objFile = objFSO.OpenTextFile(&#8220;c:\\scripts\\test.txt&#8221;, ForReading)<\/p>\n<p>Do Until objFile.AtEndOfStream\n    strLine = objFile.ReadLine\n    strLine = Trim(strLine) &amp; vbCrLf\n    strText = strText &amp; strLine\nLoop<\/p>\n<p>objFile.Close<\/p>\n<p>Set objFile = objFSO.OpenTextFile(&#8220;c:\\scripts\\test.txt&#8221;, ForWriting)\nobjFile.Write strText\nobjFile.Close\n<\/PRE>\n<P>This script starts out by defining a pair of constants: ForReading and ForWriting. Because of the quirks of the <B>FileSystemObject<\/B> (the scripting object used to work with text files) we have to open the log file twice to accomplish our task: once to read from the file and once to write the modified values back to the file. These constants simply tell the script which operation &#8211; reading or writing &#8211; we want to perform. (That\u2019s one of the quirks we were talking about: you can open a file for reading or for writing, but you can\u2019t do both at the same time.)<\/P>\n<P>After defining the constants we create an instance of the FileSystemObject and then use the <B>OpenTextFile<\/B> method to open the file C:\\Scripts\\Test.txt for reading. That brings us to this block of code:<\/P><PRE class=\"codeSample\">Do Until objFile.AtEndOfStream\n    strLine = objFile.ReadLine\n    strLine = Trim(strLine) &amp; vbCrLf\n    strText = strText &amp; strLine\nLoop\n<\/PRE>\n<P>What we\u2019re doing here is using the <B>ReadLine<\/B> method to read the file line-by-line. When we first enter the Do Until loop we read the first line in the text file and store that value in a variable named strLine. That means strLine will equal this:<\/P><PRE class=\"codeSample\">Ken Myer          *\n<\/PRE>\n<P>Now comes that vintage programming magic you\u2019ve been waiting for. In the next line of code we use the <B>Trim<\/B> function to remove all the blank spaces before and after our string (we also tack on a carriage return-linefeed to make sure that this value will be written as a separate line in the text file):<\/P><PRE class=\"codeSample\">strLine = Trim(strLine) &amp; vbCrLf\n<\/PRE>\n<P>As you probably already guessed, the Trim function automatically removes extraneous blank spaces before and after a string. That means that strLine is now equal to this (remember, the asterisk isn\u2019t really there, we\u2019re just using it to indicate the end of the data):<\/P><PRE class=\"codeSample\">Ken Myer*\n<\/PRE>\n<P>Cool, huh? We then add the value of strLine to a variable named strText, a variable we use to keep track of all the text file lines we trim:<\/P><PRE class=\"codeSample\">strText = strText &amp; strLine\n<\/PRE>\n<P>And then we loop around and repeat the process with the next line in the text file, a cycle which continues until we\u2019ve run out of lines to read (or, in more technical terms, until the <B>AtEndOfStream<\/B> property is true).<\/P>\n<P>The rest is easy. We close the file Test.txt and then immediately reopen it, this time for writing. With the file open for writing we call the <B>Write<\/B> method to write the value of strText to the file, close the file and, not coincidentally, call it a day. If you open the file Test.txt now, you\u2019ll see the data has been trimmed nice and neat:<\/P><PRE class=\"codeSample\">Ken Myer*\nPilar Ackerman*\nGail Erickson*\n<\/PRE>\n<P>We\u2019d like to see your fancy-schmancy Blackberry device or cappuccino machine do <I>that<\/I>!<\/P>\n<P>Incidentally, there are two related functions you might find useful. <B>LTrim<\/B> trims excess spaces only from the <I>beginning<\/I> (the left side) of a string. In other words, you end up with data like this:<\/P><PRE class=\"codeSample\">Ken Myer          *\nPilar Ackerman     *\nGail Erickson     *\n<\/PRE>\n<P>Conversely, <B>RTrim<\/B> trims excess black spaces from only the end (right side) of a string:<\/P><PRE class=\"codeSample\">Ken Myer*\n                    Pilar Ackerman*\n     Gail Erickson*\n<\/PRE>\n<P>There you have it, KS. And remember, if you ever have a question about something no modern human being is likely to know how to do (like, say, change the channel without using the remote), well, now you know where to go for help.<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! We have a custom in-house application that writes data to a log file. The problem is that the data often has a bunch of blank spaces before and after it. How can I remove all the blank spaces that come before and after my data?&#8212; KS Hey, KS. You might find this [&hellip;]<\/p>\n","protected":false},"author":595,"featured_media":87096,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[40,3,4,21,5],"class_list":["post-67403","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-filesystemobject","tag-scripting-guy","tag-scripting-techniques","tag-string-manipulation","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! We have a custom in-house application that writes data to a log file. The problem is that the data often has a bunch of blank spaces before and after it. How can I remove all the blank spaces that come before and after my data?&#8212; KS Hey, KS. You might find this [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/67403","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/users\/595"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/comments?post=67403"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/67403\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media\/87096"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media?parent=67403"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=67403"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=67403"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}