JavaScript中为String对象扩展Trim、LTrim和RTrim方法
作者:函数茶馆时间:2026-10-21 23:30:46浏览:332
本文介绍如何在JavaScript中通过扩展String原型对象,手动实现Trim、LTrim和RTrim三个字符串处理方法。利用正则表达式匹配首尾空白字符,分别实现去除两端、左侧及右侧空格的功能,并提供完整的代码示例与使用演示。
扩展String原型实现去空格方法
接下来,我们将利用这一属性为String对象扩展三个方法:Trim、LTrim和RTrim,其功能与VBScript中的同名函数保持一致。
具体实现代码如下:
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, "");
} 实现过程十分简洁,下面通过一个实际案例来演示其用法。
Trim方法使用示例
示例代码如下:
<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>作者最新文章
JS split切割后出现空字符串怎么过滤
2026-11-05 16:00:30
在 React 或 Vue 项目中封装使用 JS 节流防抖
2026-11-05 15:27:29
JavaScript中怎么将带小数的字符串转为整数?
2026-11-05 14:32:38
怎么用JavaScript策略模式重构电商促销计算逻辑?
2026-11-05 14:01:09
JS使用constructor判断数据类型可靠吗
2026-11-05 13:49:41
