Tuesday, January 12, 2010

Removing Extra space from text using javascript

Remove spaces from input...


str1 = "someone @ somewhere . com"
str1 = str1.replace(/\s+/g,"");
document.write(str1);


Trim spaces from the beginning of a string


str2 = " This is a test!";
str2 = str2.replace(/^\s+/,"");
document.write(str2);


Trim spaces from the end of a string

str3 = "This is a test! ";
str3 = str3.replace(/\s+$/,"");
document.write(str3);


Remove extra spaces from within a string
and replace them with ONE space

str4 = "This is a test!";
str4 = str4.replace(/\s+/g," ");
document.write(str4);


Here's how to combine the last three
examples into one statement!

str5 = " This is a test! ";
str5 = str5.replace(/^\s+/,"").replace(/\s+$/,"").replace(/\s+/g," ");
document.write(str5);

No comments:

Post a Comment