js trim()的用法

本文介绍了如何在JavaScript中实现自定义的trim方法,包括删除字符串左边、右边以及两边的空格,并解释了正则表达式的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为js中没有trim这个方法,所以我们要自己编写一个这样的方法

1删除字符串左边的所有空格   

  function Lefttrim(str) { //删除左端的空格
            return str.replace(/^\s*/g, ""); //把空格替换为空
        }

2删除字符串右边的所有空格  

     function Righttrim(str) { //删除右端的空格
            return str.replace(/\s*$/g, ""); //把空格替换为空
        }

3删除字符串两边的所有空格  

     function trim(str) { //删除左右两端的空格
            return str.replace(/(^\s*)|(\s*$)/g, ""); //把空格替换为空
        }

4以上用到的正则表达式解释

^ 表示开始

$ 表示结束

* 表示出现0-N次

| 表示“或者”

g 表示全部

<html xmlns="http://www.w3.org/1999/xhtml"> <style type="text/css">table{border-collapse:collapse;table-layout:fixed;border-spacing:0;empty-cells:show;}a{text-decoration:none;font-family:Verdana;font-size:13px;font-weight:bold;background-color:rgb(246,246,246);}a:hover{text-decoration:none;}.X1{position:absolute;left:0em;top:0px;}</style> <body alink="#000000" vlink="#000000" link="#000000" bgColor="#808080"> <table border="0"> <tr class="X1"> <td> <a href="Sheet 1 部门年度评优申请汇总表 .html" target="top" id="0" onclick="click_method(this.id);">&nbsp;Sheet&nbsp;1&nbsp;&nbsp;部门年度评优申请汇总表&nbsp;&nbsp;</a> </td> <td> <a href="附 年度评优申请表.html" target="top" id="1" onclick="click_method(this.id);">&nbsp;附&nbsp;年度评优申请表&nbsp;</a> </td> </tr> </table> </body> <script>var showId="0";var clickId="0";var original_backcolor = ["",""];var click_backcolor = ["",""];document.getElementById(clickId).style.background=click_backcolor[parseInt(clickId)];document.getElementById(clickId).style.borderBottomColor = original_backcolor[parseInt(clickId)]; document.getElementById(clickId).style.borderBottomStyle = "solid"; document.getElementById(clickId).style.borderBottomWidth = "4"; function click_method(id){document.getElementById(showId).style.background=original_backcolor[parseInt(showId)];document.getElementById(showId).style.borderBottomColor = ""; document.getElementById(showId).style.borderBottomStyle = ""; document.getElementById(showId).style.borderBottomWidth = ""; clickId=id;document.getElementById(clickId).style.background=click_backcolor[parseInt(clickId)];document.getElementById(clickId).style.borderBottomColor = original_backcolor[parseInt(clickId)]; document.getElementById(clickId).style.borderBottomStyle = "solid"; document.getElementById(clickId).style.borderBottomWidth = "4"; showId=clickId;};</script> </html> 如何获取href后的信息呢
最新发布
08-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值