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));-----------""