導航:首頁 > 編程語言 > javascripttrim

javascripttrim

發布時間:2025-08-21 00:25:06

A. javascript內實現trim的方法

首先是把/(^\s*)|(\s*$)/g 替換為""

然後,/.../g 裡面的,是表示放置通配符的地方,g代表全局參數
(^\s*)或者(\s*$)都將被替換為""

匹配首尾空白字元的正則表達式:^\s*|\s*$
可以用來刪除行首行尾的空白字元(包括空格、製表符、換頁符等等),非常有用的表達式

B. javascript的trim用法

方案一:
以原型方式調用,即obj.trim()形式,方式簡單且使用方面廣泛,定義方式如下:

<script language=」javascript」>
/**
* 刪除左右兩端的空格
*/
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,」);
}
</script>

使用示例如下:

<script type=」text/javascript」>
alert(document.getElementById(』abc』).value.trim());
alert(document.getElementById(』abc』).value.ltrim());
alert(document.getElementById(』abc』).value.rtrim());
</script>

方案二:
工具方式調用,trim(obj)的形式,此方式用於特殊處理需要,定義方式如下:
<script type=」text/javascript」>
/**
* 刪除左右兩端的空格
*/
function trim(str)
{
return str.replace(/(^\s*)|(\s*$)/g, 」);
}
/**
* 刪除左邊的空格
*/
function ltrim(str)
{
return str.replace(/(^\s*)/g,」);
}
/**
* 刪除右邊的空格
*/
function rtrim(str)
{
return str.replace(/(\s*$)/g,」);
}
</script>

使用示例如下:

<script type=」text/javascript」>
alert(trim(document.getElementById(』abc』).value));
alert(ltrim(document.getElementById(』abc』).value));
alert(rtrim(document.getElementById(』abc』).value));
</script>

閱讀全文

與javascripttrim相關的資料

熱點內容
網路中常用的傳輸介質 瀏覽:518
文件如何使用 瀏覽:322
同步推密碼找回 瀏覽:865
樂高怎麼才能用電腦編程序 瀏覽:65
本機qq文件為什麼找不到 瀏覽:264
安卓qq空間免升級 瀏覽:490
linux如何刪除模塊驅動程序 瀏覽:193
at89c51c程序 瀏覽:329
怎麼創建word大綱文件 瀏覽:622
裊裊朗誦文件生成器 瀏覽:626
1054件文件是多少gb 瀏覽:371
高州禁養區內能養豬多少頭的文件 瀏覽:927
win8ico文件 瀏覽:949
仁和數控怎麼編程 瀏覽:381
項目文件夾圖片 瀏覽:87
怎麼在東芝電視安裝app 瀏覽:954
plc顯示數字怎麼編程 瀏覽:439
如何辨別假網站 瀏覽:711
寬頻用別人的賬號密碼 瀏覽:556
新app如何佔有市場 瀏覽:42

友情鏈接