Mega Code Archive

 
Categories / JavaScript DHTML / Development
 

Trim a string with regular expression from both sides

<HTML> <HEAD> <TITLE>Strim a tring</TITLE> <SCRIPT> function ltrim(testStr) {    if (testStr == "")       return "";    else {       var pattern = /[^\s]+.*/;       result = testStr.match(pattern);       return result[0];    } } function rtrim(testStr) {    if (testStr == "")       return "";    else {       var pattern = /.*[\S]/;       result = testStr.match(pattern);       return result[0];    } } function trim(testStr) {    return rtrim(ltrim(testStr)); } </SCRIPT> </HEAD> <BODY> <FORM name="theForm"> <TABLE> String for trimming: <INPUT type=text name=testStr size=60> <INPUT type=button name="theButton" value="Trim" onClick="document.theForm.display.value = trim(document.theForm.testStr.value)";> <INPUT type=button name="theButton" value="Clear" onClick='document.theForm.testStr.value=""; document.theForm.display.value=""'> Trimmed string: <INPUT type=text name=display size=60/> </FORM>   </BODY> </HTML>