Home > Web Front-end > JS Tutorial > body text

jQuery implements a method to add specific content to a string according to a specified length_jquery

WBOY
Release: 2016-05-16 16:10:01
Original
1153 people have browsed it

The example in this article describes the jQuery method of adding specific content to a string according to a specified length. Share it with everyone for your reference. The specific analysis is as follows:

In a recent project, mobile phone numbers needed to be separated by identifiers of a certain length to facilitate reading. After searching online for a while, I found that there was no suitable code, so I handwrote a function myself, which can add the specified length to a string. Insert the separator and friends in need can take it.

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;//长度
  var num=len/sn;//分段数
  var start;
  var end;
  //len%sn //能否完整分段 0:是
  for(i=0;i<num;i+=1){
    if (len%sn!=0){//不能完整分段
      start=i*sn-1;
      end=i*sn+(sn-1);
    }else{
      start=i*sn;
      end=(i+1)*sn;
    }
    start=start<0&#63;0:start;
    if (end<=len){
      tmp=str.substring(start,end);
    }
    newstr+=(end>=len)&#63;tmp:tmp+flg;
  }
  split_str=newstr;
  return newstr;
}
$(function(){
  var phone=$("#phone");
  phone.blur(function(){//失去焦点时触发
    var cont=phone.val();
    cont=jQuery.trim(cont);
    var str_p='-';//拆分符号
    var s=4;//每段长度
    if (!cont||split_str==cont) return false;
 //焦点再次离开时检查内容有无变化
    phone.val(insert_flg(cont,str_p,s));
    })
})
Copy after login

I hope this article will be helpful to everyone’s jQuery programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!