js中实现trim、trimEnd和trimStart函数
开发过程中需要再js中实现拼接字符串形成一个文件访问地址,但要求不能出现//的情况(除了http://),如:域名+"/"+文件夹 + "/" + 文件名,拼接后出现类似 http://www.baidu.com//test//1111.apk这样的地址,所以需要把配置中域名和文件夹后面的/符号去掉再进行拼接,赶时间,来不及用正则实现,用最土的办法实现功能
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);
};
////测试
var hostStr = "http://dev.test.com/"; //配置文件中读到的域名地址
var floderStr = "test/"; //配置文件中读到的文件夹地址
var fileName = "2012081317252135.pgn"
var iconPath = hostStr.trimEnd('/') + "/" + floderStr.trimEnd('/') + "/" + fileName;
alert(iconPath); //输出为http://dev.test.com/test/2012081317252135.pgn
//暂时先用着,有时间再用正则写一个。
浙公网安备 33010602011771号