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());
JavaScript中字符串处理的一些函数的更多相关文章
- JavaScript中字符串分割函数split用法实例
这篇文章主要介绍了JavaScript中字符串分割函数split用法,实例分析了javascript中split函数操作字符串的技巧,非常具有实用价值,需要的朋友可以参考下 本文实例讲述了JavaSc ...
- JavaScript中常见的数组操作函数及用法
JavaScript中常见的数组操作函数及用法 昨天写了个帖子,汇总了下常见的JavaScript中的字符串操作函数及用法.今天正好有时间,也去把JavaScript中常见的数组操作函数及用法总结一下 ...
- SQL SERVER 将表中字符串转换为数字的函数 (详询请加qq:2085920154)
在SQL SERVER 2005中,将表中字符串转换为数字的函数共2个:1. convert(int,字段名) 例如:select convert(int,'3')2. cast(字段名 as i ...
- javascript中字符串常用操作整理
javascript中字符串常用操作整理 字符串的操作在js中非常频繁,也非常重要.以往看完书之后都能记得非常清楚,但稍微隔一段时间不用,便会忘得差不多,记性不好是硬伤啊...今天就对字符串的一些常用 ...
- JavaScript中字符串的match与replace方法
1.match方法 match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配. match()方法的返回值为:存放匹配结果的数组. 2.replace方法 replace() 方 ...
- 一篇文章把你带入到JavaScript中的闭包与高级函数
在JavaScript中,函数是一等公民.JavaScript是一门面向对象的编程语言,但是同时也有很多函数式编程的特性,如Lambda表达式,闭包,高阶函数等,函数式编程时一种编程范式. funct ...
- JavaScript中字符串截取函数slice()、substring()、substr()
在js中字符截取函数有常用的三个slice().substring().substr()了,下面我来给大家介绍slice().substring().substr()函数在字符截取时的一些用法与区别吧 ...
- JavaScript中的闭包和匿名函数
JavaScript中的匿名函数及函数的闭包 1.匿名函数 2.闭包 3.举例 4.注意 1.匿名函数 函数是JavaScript中最灵活的一种对象,这里只是讲解其匿名函数的用途.匿名函数:就是没 ...
- JavaScript中的闭包与匿名函数
知识内容: 1.预备知识 - 函数表达式 2.匿名函数 3.闭包 一.函数表达式 1.定义函数的两种方式 函数声明: 1 function func(arg0, arg1, arg2){ 2 // 函 ...
随机推荐
- List 集合转换为String
开发中会用到把 List<string> 的内容拼接成以逗号分隔的字符串的形式,现总结如下: 方法一: public String listToString(List list, cha ...
- u-boot支持yaffs映像烧写的补丁
u-boot的nand flash驱动有两个版本,似乎是以u-boot1..5为分界点的,之前的版本使用的是自己写的nand flash驱动,而后面的版本使用的是linux内核中nand flash的 ...
- Objective-C:内存管理的小结
内存管理: 1.OC的对象都是分配在堆里的 Perosn *person = [[Person alloc]init]; Person *person //指针类型的 ...
- 我的SQL里哪个语句占用的CPU最多?
可以使用下面的语句来得到 SELECT SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1, ( (CASE qs.statement_end_off ...
- 【Gson】简介 文档 基本使用 示例
简介 new TypeToken<List<Person>>() {}.getType() 1 1 1 new TypeToken<List<Person> ...
- permission 权限 列表 6.0 运行时【案例】
demo地址:https://github.com/baiqiantao/PermissionTest.git <uses-permission android:name="andro ...
- 理解js中的new
new 操作符 在有上面的基础概念的介绍之后,在加上new操作符,我们就能完成传统面向对象的class + new的方式创建对象,在Javascript中,我们将这类方式成为Pseudoclassic ...
- UML解惑:图说UML中的六大关系
UML定义的关系主要有六种:依赖.类属.关联.实现.聚合和组合.这些类间关系的理解和使用是掌握和应用UML的关键,而也就是这几种关系,往往会让初学者迷惑.这里给出这六种主要UML关系的说明和类图描述, ...
- 【架构】Kubernetes和Spring Cloud哪个部署微服务更好?
Spring Cloud 和Kubernetes都自称自己是部署和运行微服务的最好环境,但是它们在本质上和解决不同问题上是有很大差异的.在本文中,我们将看到每个平台如何帮助交付基于微服务的架构(MSA ...
- [转]DOM 中 Property 和 Attribute 的区别
angular的文档: https://angular.io/guide/template-syntax#property-binding https://blog.csdn.net/sunq1982 ...