关于字符串的几个有用函数
1、测试字符串长度(中英文)
function strLen(s)
{
var i,str1,str2,str3,nLen;
str1 = s.value;
nLen = 0;
for(i=1;i<=str1.length;i++)
{
str2=str1.substring(i-1,i)
str3=escape(str2);
if(str3.length>3)
{
nLen = nLen + 2;
}
else
{
nLen = nLen + 1;
}
}
return nLen;
}
2、替换
function Replace(s1,s2,s3)
{
var len1 , len2 , i;
var str1 , str2 ;
str1 = s1;
len1 = str1.length;
len2 = s2.length;
if (len2 > len1)
return s1;
for (i=1;i<= len1-len2+1 ; i++)
{
str2 = str1.substring(i-1,i-1+len2);
if (str2 == s2)
{
str1 = str1.substring(0,i-1) + s3 + str1.substring(i+len2-1,len1 );
i = 0;
len1 = str1.length;
}
}
return str1;
}
3、查找
function Pos(s1,s2)
{
var len1 , len2 , i,flag;
var str1 , str2 ;
str1 = s1;
len1 = str1.length;
len2 = s2.length;
if (len2==0 || len1==0)
return 0;
flag = false;
if (len2 > len1)
return s1;
for (i=1;i<= len1-len2+1 ; i++)
{
str2 = str1.substring(i-1,i-1+len2);
if (str2 == s2)
{
flag = true;
break;
}
}
if (flag)
return i;
else
return 0;
}
- 上一篇: JavaScript 的变量
- 下一篇: 各种媒体在线播放代码