Friday, August 3, 2007

Remove White Space In String Using Regular Expression in JavaScript

<script language="javascript">
function rmWhiteSpace()

var str = document.getElementById('txt1').value;

str = str.replace(/\s+/g,'');

document.getElementById('txt1').value = str;

// \s+ Description
// + 1 or more of previous expression.
// \s Matches any white-space character.
// Equivalent to the Unicode character categories [\f\n\r\t\v\x85\p{Z}].
// If ECMAScript-compliant behavior is specified with the ECMAScript option,
// \s is equivalent to [ \f\n\r\t\v].
<input type='text' id='txt1' value=' Click To Check' /> <input type='button' id='bt1' value='Remove White Space' onclick='rmWhiteSpace();' />

Program Demo



Anonymous said...

this is very cool, and timely - many thanks dude!

Anonymous said...

Works!!!!!! Really helped a lot.
Thank you,

Anonymous said...

Thanks for this!! I've looked all over the net and this is the first javascript that actually works in all browsers!

Nice one.

Vankayala said...
This comment has been removed by the author.
Vankayala said...

I wonder why are using \s+ with 'g' option, instead of \s with 'g'. Curious?

windows_mss said...

I Use \s+ because Character (+)

"Repeats the previous item once or more. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is matched only once."

Anonymous said...

Nice work! Thanks for sharing this with the web development community (especially those of us not so well versed with Regular Expressions!)

Nikhil Joshi said...

Thx. very useful to me

Saideep Kankarla said...

Thanks dude really it works cool.Please post more js scripts on your blog.Thanks a lot