嗨我想從兩端修剪字符串在JavaScript中,但它不能正常工作。腳本無法工作或有時從文本框中失去焦點。 我寫javascript象下面&稱其爲驗證功能如何在JavaScript中修剪字符串?
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;
}
}
你可以看看到jQuery的修剪 http://api.jquery.com/jQuery.trim/ – nozari
存在着['trim'](https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)方法。爲什麼試圖自己呢? :/ –