JavaScript中实现C#风格TrimStart、TrimEnd与Trim方法

作者:百宝袋时间:2026-10-25 19:03:29浏览:480

本文介绍在JavaScript中手动实现类似C#的TrimStart、TrimEnd及Trim字符串处理方法。通过不使用正则表达式,采用substr截取与循环判断的方式,实现去除指定前缀、后缀及默认空格的字符串操作,提供完整代码示例供参考。

JavaScript实现C#风格字符串Trim方法

鉴于许多开发者倾向于使用正则表达式来处理字符串,而作者自身对正则掌握有限,因此选择了一种更为直观朴素的方法,自行编写了相关函数。现将实现代码分享如下,期望能为遇到相同需求的开发者提供便利。


具体实现代码如下所示:

 
String.prototype.trimStart = function(trimStr){
if(!trimStr){return this;}
var temp = this;
while(true){
if(temp.substr(0,trimStr.length)!=trimStr){
break;
} 
temp = temp.substr(trimStr.length);
} 
return temp;
}; 
String.prototype.trimEnd = function(trimStr){
if(!trimStr){return this;}
var temp = this;
while(true){
if(temp.substr(temp.length-trimStr.length,trimStr.length)!=trimStr){
break;
} 
temp = temp.substr(0,temp.length-trimStr.length);
} 
return temp;
}; 
String.prototype.trim = function(trimStr){
var temp = trimStr;
if(!trimStr){temp=" ";}
return this.trimStart(temp).trimEnd(temp);
}; 

上述代码的使用方式较为直观,此处不再赘述。若在使用过程中发现任何问题或建议,欢迎指出,谢谢!

作者最新文章