javascript截取字符串(支持中英文混合)

javascript截取字符串(支持中英文混合)

<script type="text/javascript">

var sub=function(str,n){
  var r=/[^\x00-\xff]/g;
  if(str.replace(r,"mm").length<=n){return str;}
  var m=Math.floor(n/2);
  for(var i=m;i<str.length;i++){
      if(str.substr(0,i).replace(r,"mm").length>=n){
          return str.substr(0,i)+"...";
      }
  }
  return str;
}
alert(sub('字符串截取Javascript处理总结(Js截取中文字符串总结)',15))

</script>

 

 

用js方法substring()

var str = "0123456789"; 
alert(str.substring(0));------------"0123456789" 
alert(str.substring(5));------------"56789" 
alert(str.substring(10));-----------"" 
alert(str.substring(12));-----------"" 
alert(str.substring(-5));-----------"0123456789" 
alert(str.substring(-10));----------"0123456789" 
alert(str.substring(-12));----------"0123456789" 
alert(str.substring(0,5));----------"01234" 
alert(str.substring(0,10));---------"0123456789" 
alert(str.substring(0,12));---------"0123456789" 
alert(str.substring(2,0));----------"01" 
alert(str.substring(2,2));----------"" 
alert(str.substring(2,5));----------"234" 
alert(str.substring(2,12));---------"23456789" 
alert(str.substring(2,-2));---------"01" 
alert(str.substring(-1,5));---------"01234" 
alert(str.substring(-1,-5));--------"" 

用js方法substr()

var str = "0123456789"; 
alert(str.substr(0));---------------"0123456789" 
alert(str.substr(5));---------------"56789" 
alert(str.substr(10));--------------"" 
alert(str.substr(12));--------------"" 
alert(str.substr(-5));--------------"0123456789" 
alert(str.substr(-10));-------------"0123456789" 
alert(str.substr(-12));-------------"0123456789" 
alert(str.substr(0,5));-------------"01234" 
alert(str.substr(0,10));------------"0123456789" 
alert(str.substr(0,12));------------"0123456789" 
alert(str.substr(2,0));-------------"" 
alert(str.substr(2,2));-------------"23" 
alert(str.substr(2,5));-------------"23456" 
alert(str.substr(2,12));------------"23456789" 
alert(str.substr(2,-2));------------"" 
alert(str.substr(-1,5));------------"01234" 
alert(str.substr(-1,-5));-----------""

 

posted @ 2013-06-18 15:23  cssfirefly  阅读(8449)  评论(1编辑  收藏  举报
foot