<html>
<SCRIPT LANGUAGE="JavaScript">
<!--
// ALLTrim(), LRTrim() , Ltrim() , RTrim()
String.prototype.ALLTrim = function(){
// 去除所有空格
return this.replace(/\s+/g,"");
}
String.prototype.LRTrim = 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>
<body>
<input type="text" value=" 到 处 都 是 空 格 " id="space" size="30">
<input type="button" id="btnId1" value="去全部空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.ALLTrim();document.getElementById('space').select();">
<input type="button" id="btnId2" value="去前后空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.LRTrim();document.getElementById('space').select();">
<input type="button" id="btnId3" value="去前空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.LTrim();document.getElementById('space').select();">
<input type="button" id="btnId4" value="去后空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.RTrim();document.getElementById('space').select();">
<input type="button" id="btnId5" value=" 还 原 " onclick="javascript:document.getElementById('space').value=' 到 处 都 是 空 格 ';">
</body>
</html>js 去空格
JavaScript字符串修剪方法
最新推荐文章于 2020-07-23 13:19:49 发布
本文介绍了一种使用JavaScript自定义方法来实现字符串两端、左侧及右侧空白字符去除的技术方案。通过扩展String原型,实现了ALLTrim(去除所有空格)、LRTrim(去除两端空格)、LTrim(去除左侧空格)和RTrim(去除右侧空格)等功能,并提供了简单的HTML页面以演示这些方法的应用。
579

被折叠的 条评论
为什么被折叠?



