JavaScript中字符串处理的一些函数
废话,不多说,直接上代码
<script type="text/javascript"> (function(){ var methods = { camelize: function() { /** * Returns string with all instances of * "-word" replaced with "Word", E.g. * "background-color" -> "backgroundColor" **/ return this.replace(/\-(\w)/g, function( $0, $1 ) { return $1.toUpperCase(); }); }, contains: function( what ) { /** * Returns boolean indicating whether * or not a substring exists within the string **/ what = typeof what === 'string' ? what : what.toString(); return this.indexOf( what ) > -1; }, count: function( what ) { /** * Returns a number indicating how many times * a substring or regex is matched within the string **/ if ( Object.prototype.toString.call(what) !== '[object RegExp]' ) { what = what.toString().replace(/\$\^\[\]\{\}\(\)\?\:\.\+\*/g, '\\$1'); } what = RegExp( what ? what.source : '.', 'g' ); return (this.match( what ) || []).length; }, enclose: function( a, b ) { /** * Returns string with all instances * of -w replaced with W, e.g. * "background-color" -> "backgroundColor" **/ return (a = a || '') + this + (b ? b : a); }, extract: function( regex, n ) { /** * Matches the string against the passed regex * and the returns the group specified by _n_ * * E.g. * ('hi @boo and @adam').extract(/@(\w+)/g, 1); * => ['boo', 'adam'] * * If the regex is global then an array is returned * otherwise just the matched group is returned. **/ n = n === undefined ? 0 : n; if ( !regex.global ) { return this.match(regex)[n] || ''; } var match, extracted = []; while ( (match = regex.exec(this)) ) { extracted[extracted.length] = match[n] || ''; } return extracted; }, forEach: function( fn ) { /** * Runs the passed function on every character, * similar to Array.prototype.forEach **/ var c, i = -1; while ( (c = this[++i]) ) { fn.call( this, c, i ); } return true; }, forEachWord: function( fn ) { /** * Runs the passed function on every word, * similar to Array.prototype.forEach **/ var string = this, i = -1; string.replace(/\b([\w\-]+)\b/g, function( match, word ){ fn.call( string, word, ++i ); return match; }); return true; }, linkify: function( replacement ) { /** * Returns a string with all URLs replaced * with HTML anchor tags. **/ return this.replace(/(^|\s)((?:f|ht)tps?:\/\/[^\s]+)/g, replacement || '$1<a href="$2">$2</a>'); }, many: function( n ) { /** * Returns a string which is made up of * _n_ instances of the original string. * E.g. "a".many(3) => "aaa" **/ return Array(n ? n + 1 : 2).join(this); }, randomize: function() { /** * Randomizes a string; messes up all the characters. * E.g. "abcdef".randomize() => "bcfdea" **/ return this.split('').sort(function(){ return Math.random() > 0.5 ? -1 : 1; }).join(''); }, remove: function( what ) { /** * Returns a string with all matches of * what (regex) removed. **/ return this.replace( what || /./g, '' ); }, removefromLength : function (A,B) { /** * Returns string * How long is where to begin a string is removed **/ var s=''; if(A>0)s=this.substring(0,A); if(A+B<this.length)s+=this.substring(A+B,this.length); return s; }, reverse: function() { /** * Returns the string, reversed. **/ return this.split('').reverse().join(''); }, shorten: function( length, token ) { /** * Shortens the string by the specified amount * and appends the token. * E.g. * "this is a long sentance".shorten(10, '...'); * => "this is a ..." **/ var substrd = this.substring( 0, length || this.length ); return substrd + ( substrd === this ? '' : (token || '') ); }, sort: function() { /** * Runs the Array.sort() method on every * character of the string. **/ return Array.prototype.sort.apply( this.split(''), arguments ).join(''); }, toDOM: function() { /** * Returns the DOM representation of the string, * in the form of an array of DOM nodes. **/ var temp = document.createElement('div'); temp.innerHTML = this; return Array.prototype.slice.call( div.childNodes ); }, trim: function() { /** * Returns the string with leading and * trailing spaces removed. **/ return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }, wrap: function( width, brk, cut ) { /** * Wraps the string. * E.g. * "the dog realllly wet".wrap(4, '<br/>') * => "the <br/>dog <br/>realllly <br/>wet" **/ brk = brk || '\n'; width = width || 75; cut = cut || false; if (!this) { return this; } var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)'); return this.match( RegExp(regex, 'g') ).join( brk ); }, // endsWith : function (A,B) { /** * To determine whether a string to specify the end of the string **/ var C=this.length; var D=A.length; if(D>C)return false; if(B) { var E=new RegExp(A+'$','i'); return E.test(this); }else return (D==0||this.substr(C-D,D)==A); }, // startsWith : function(str) { /** * To determine whether a string starts with the specified string **/ return this.substr(0, str.length) == str; }, replaceAll:function (a,b) { /** * replaceAll * eg:str.ReplaceAll([/a/g,/b/g,/c/g],["aaa","bbb","ccc"]) **/ var c=this; for(var i=0;i<a.length;i++) { c=c.replace(a[i],b[i]); }; return C; }, isEmail : function() { /** * Returns boolean and * Check whether the correct email **/ return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(this); }, inTrim:function(s){ /** * Returns string * remove the Spaces in the string **/ return s.replace( /\s/g,""); }, checkPassWordLevelA:function() { /** * Returns number * Determine the password security level **/ var n=0; if (/\d/.test(this)) n ++; if (/[a-z]/.test(this)) n ++; if (/[A-Z]/.test(this)) n ++; if (this.length == 6) n=1; return n; }, checkPassWordLevelB : function() { /** * Returns number * Determine the password security level **/ var grade=0; if (this.length >= 6 && this.length <= 9) { grade = 1; } if (this.length >= 10 && this.length <= 15) { grade = 2; } if (this.length >= 16 && this.length <= 20) { grade = 3; } return grade; }, isIDCard : function() { /** * Returns boolean * Whether effective id card (China **/ var iSum=0; var info=""; var sId = this; var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}; if(!/^\d{17}(\d|x)$/i.test(sId)) { return false; } sId=sId.replace(/x$/i,"a"); if(aCity[parseInt(sId.substr(0,2))]==null) { return false; } var sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2)); var d=new Date(sBirthday.replace(/-/g,"/")) if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate())) { return false; } for(var i = 17;i>=0;i--) { iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11); } if(iSum%11!=1) { return false; } return true; }, isNumeric : function(flag) { /** * Verify whether the Numbers **/ if(isNaN(this)) { return false; } switch(flag) { case null: case "": return true; case "+": return /(^\+?|^\d?)\d*\.?\d+$/.test(this); case "-": return /^-\d*\.?\d+$/.test(this); case "i": return /(^-?|^\+?|\d)\d+$/.test(this); case "+i": return /(^\d+$)|(^\+?\d+$)/.test(this); case "-i": return /^[-]\d+$/.test(this); case "f": return /(^-?|^\+?|^\d?)\d*\.\d+$/.test(this); case "+f": return /(^\+?|^\d?)\d*\.\d+$/.test(this); case "-f": return /^[-]\d*\.\d$/.test(this); default: return true; } }, checkChinese : function() { /** * Returns boolean * Check whether the Chinese characters **/ var reg=/^[\u0391-\uFFE5]+$/ ; // [\u4E00-\u9FA5]; return reg.test(this); }, isMobile : function() { /** * Returns string * Check whether a mobile phone number eg. 13723450922 **/ var reg = /^(13|14|15|17|18)[0-9]{9}$/; return reg.test(this); }, ChineseLength : function() { /** * Returns boolean * Returns the length of the character, a Chinese is 2 **/ return this.replace(/[^\x00-\xff]/g,"**").length; }, format : function(){ var args = arguments; return this.replace(/\{(\d+)\}/g,function(m,i,o,n){ return args[i]; }); } }; /* This is where each method is added to String.prototype ( assuming it's not already there ) */ for (var method in methods) { String.prototype[method] = String.prototype[method] || methods[method]; } })(); var s = '中国人'; console.log(s.ChineseLength());
- 作者:踏雪无痕
- 出处:http://www.cnblogs.com/chenpingzhao/
- 本文版权归作者和博客园共有,如需转载,请联系 pingzhao1990#163.com