Monday, 16 March 2015

Remove Extra Spaces Using JavaScript

  1. Remove Extra Spaces Using JavaScript

This simple script uses regular expressions to remove unwanted extra spaces from a block of text. The following example illustrates the script (you can paste your own text here if you like):
 
To use this script, place the following code in the document head:
function
trimSpaces(){
        s
= document.getElementById("textString").value;
        s
= s.replace(/(^\s*)|(\s*$)/gi,"");
        s
= s.replace(/[ ]{2,}/gi," ");
        s
= s.replace(/\n /,"\n");
       
document.getElementById("textString").value
= s;
}
Place the following code in the document body (modify to suit your needs):
<textarea
name="textString" id="textString" cols="50"
rows="4">
 This
is a block of text with some  extra    spaces in it.   Click the
button to remove them. 
</textarea>


No comments:

Post a Comment