在javascript中的string对象没有trim方法,所以trim功能需要自己实现:
代码如下:
Java代码
﹤scriptlanguage=”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﹥
﹤scriptlanguage=”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﹥
使用如下
Java代码
﹤scripttype=”text/javascript”﹥
alert(document.getElementById(’abc’).value.trim());
alert(document.getElementById(’abc’).value.ltrim());
alert(document.getElementById(’abc’).value.rtrim());
﹤/script﹥
javascript trim方法
最新推荐文章于 2024-03-19 03:32:57 发布
本文介绍如何在JavaScript中自定义实现字符串的Trim方法,包括去除字符串首尾、仅左侧或仅右侧空白字符的功能,并提供了使用示例。
226

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



