在Javascript中為String對象添加trim,ltrim,rtrim方法
更新時間:2006年09月22日 00:00:00 作者:
利用Javascript中每個對象(Object)的prototype屬性我們可以為Javascript中的內(nèi)置對象添加我們自己的方法和屬性。
以下我們就用這個屬性來為String對象添加三個方法:Trim,LTrim,RTrim(作用和VbScript中的同名函數(shù)一樣)
怎么樣,簡單吧,下面看一個使用的實例:
<script language=javascript>
String.prototype.Trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}
var s = " leading and trailing spaces ";
window.alert(s + " (" + s.length + ")");
s = s.Trim();
window.alert(s + " (" + s.length + ")");
</script>
復(fù)制代碼 代碼如下:
String.prototype.Trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.LTrim = function()
{
return this.replace(/(^\s*)/g, "");
}
String.prototype.Rtrim = function()
{
return this.replace(/(\s*$)/g, "");
}
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.LTrim = function()
{
return this.replace(/(^\s*)/g, "");
}
String.prototype.Rtrim = function()
{
return this.replace(/(\s*$)/g, "");
}
怎么樣,簡單吧,下面看一個使用的實例:
復(fù)制代碼 代碼如下:
<script language=javascript>
String.prototype.Trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}
var s = " leading and trailing spaces ";
window.alert(s + " (" + s.length + ")");
s = s.Trim();
window.alert(s + " (" + s.length + ")");
</script>
相關(guān)文章
帶有定位當(dāng)前位置的百度地圖前端web api實例代碼
這篇文章主要介紹了帶有定位當(dāng)前位置的百度地圖前端web api實例代碼 的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-06-06JavaScript ES6中類與模塊化管理超詳細(xì)講解
JavaScript中的模塊化是指將每個js文件會被認(rèn)為單獨一個的模塊。模塊之間是互相不可見的。如果一個模塊需要使用另一個模塊,那么需要通過指定語法來引入要使用的模塊,而且只能使用引入模塊所暴露的內(nèi)容2023-01-01Bootstrap中定制LESS-顏色及導(dǎo)航條(推薦)
這篇文章主要介紹了Bootstrap中定制LESS-顏色及導(dǎo)航條的相關(guān)資料,非常不錯具有參考借鑒價值,感興趣的朋友一起看看吧2016-11-11JS中如何實現(xiàn)點擊a標(biāo)簽返回頁面頂部的問題
這篇文章主要介紹了JS中實現(xiàn)點擊a標(biāo)簽返回頁面頂部的問題,非常不錯,具有參考借鑒價值,需要的的朋友參考下吧2017-01-01