jQuery implements the method of adding specific content to a string at a specified length
- 2020-05-12 02:13:44
- OfStack
This article demonstrates an example of how jQuery implements strings that add specific content at a specified length. Share with you for your reference. The specific analysis is as follows:
In a recent project, it is required to separate the mobile phone number by 1 with an identifier, which is easy to read. If you find 1 on the Internet, you will find that there is no suitable code, so you write a function by yourself. You can insert separator into the string according to the specified length.
var split_str=false;
function insert_flg(str,flg,sn){
str=str.replace(new RegExp(flg,"g"),"");
var newstr="";
var tmp;
var len=str.length;// The length of the
var num=len/sn;// Number of segments
var start;
var end;
//len%sn // Can you complete the segmentation? 0 Is:
for(i=0;i<num;i+=1){
if (len%sn!=0){// Incomplete segmentation
start=i*sn-1;
end=i*sn+(sn-1);
}else{
start=i*sn;
end=(i+1)*sn;
}
start=start<0?0:start;
if (end<=len){
tmp=str.substring(start,end);
}
newstr+=(end>=len)?tmp:tmp+flg;
}
split_str=newstr;
return newstr;
}
$(function(){
var phone=$("#phone");
phone.blur(function(){// Triggered when losing focus
var cont=phone.val();
cont=jQuery.trim(cont);
var str_p='-';// Break up the symbol
var s=4;// Each length
if (!cont||split_str==cont) return false;
// Check for changes when the focus leaves again
phone.val(insert_flg(cont,str_p,s));
})
})
I hope this article has been helpful to your jQuery programming.