简体   繁体   中英

how to trim string in javascript?

Hi I am trying to trim string from both end in javascript but it not work properly.Script can't work or some times it lost focus from textbox. I am write javascript like below & calling it in validate function

function trim(s) 
        {
            if (typeof s!= "string") {
                return s;
             }
             var retValue = s;
             var ch = retValue.s(0, 1);
             while (ch == " ")
             {      retValue = retValue.substring(1, retValue.length);
                    ch = retValue.substring(0, 1);
             }
             ch = retValue.substring(retValue.length-1, retValue.length);
             while (ch == " ")
             {
                 retValue = retValue.substring(0, retValue.length-1);
                 ch = retValue.substring(retValue.length-1, retValue.length);
            }
            while (retValue.indexOf("  ") != -1)
            {
                retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
            }
                return retValue; 
        } 

       function validate() {
        // alert("Please! Enter  Farm Name");
        if (!trim(document.getElementById("<%=txtFarm_Name.ClientID%>").value)) {
            alert("Please! Enter  Farm Name");
            document.getElementById("<%=txtFarm_Name.ClientID%>").focus();
            return false;
        }

}

You could do some thing like the following

if(!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g,'');
  };
}

Once the above code is executed it can be use like the following

var str = " Hello world  ";
console.log(str.trim());

Or if jquery is being used in the project then something like the following will work too

var str = " Hello world  ";
$.trim(str);

I had written this function for trim, when the .trim() function was not available in JS way back in 2008. Some of the older browsers still do not support the .trim() function and i hope this function may help you.

TRIM FUNCTION

function trim(str)
{
    var startpatt = /^\s/;
    var endpatt = /\s$/;

    while(str.search(startpatt) == 0)
        str = str.substring(1, str.length);

    while(str.search(endpatt) == str.length-1)
        str = str.substring(0, str.length-1);   

    return str;
}

Explanation : The function trim() accept a string object and remove any starting and trailing whitespaces (spaces,tabs and newlines) and return the trimmed string. You can use this function to trim form inputs to ensure valid data to be sent.

The function can be called in the following manner as an example.

form.elements[i].value = trim(form.elements[i].value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM