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 // 函 ...
随机推荐
- Oracle WIHT AS 用法
1.with table as 相当于建个临时表(用于一个语句中某些中间结果放在临时表空间的SQL语句),Oracle 9i 新增WITH语法,可以将查询中的子查询命名,放到SELECT语句的最前面. ...
- swing入门教程
(转自http://terrificwanjun.bokee.com/) UI 组件简介 在开始学习 Swing 之前,必须回答针对真正初学者的一个问题:什么是 UI?初学者的答案是“用户界面”.但是 ...
- 如何搭建 LNMP环境
和LAMP不同的是LNMP中的N指的是是Nginx(类似于Apache的一种web服务软件)其他都一样.目前这种环境应用的也是非常之多. Nginx设计的初衷是提供一种快速高效多并发的web服务软件. ...
- hue耗流量优化
ps: 使用的hue版本为 hue-3.10.0 一.[jobbrowser刷流量] 基本一分钟刷新一次,执行GET /jobbrowser/ [17/Apr/2017 14:46:26 +0800] ...
- spring事务管理器的源码和理解
原文出处: xieyu_zy 以前说了大多的原理,今天来说下spring的事务管理器的实现过程,顺带源码干货带上. 其实这个文章唯一的就是带着看看代码,但是前提你要懂得动态代理以及字节码增强方面的知识 ...
- golang包管理工具及环境管理工具;如何下载外网的依赖包
简介: golang的包管理工具类似于java的maven.python的pip.js的npm,可以实现依赖包的统一管理:有很多:govendor.godep.glide,挑一个自己喜欢的用吧.mac ...
- 基于at91rm9200的i2c分析(DS1307实时时钟芯片)
board-ek.c 构造i2c_board_info结构体 static struct i2c_board_info __initdata ek_i2c_devices[] = { { ...
- ransom-note
https://leetcode.com/problems/ransom-note/ public class Solution { public boolean canConstruct(Strin ...
- 第九章 Redis过期策略
注:本文主要参考自<Redis设计与实现> 1.设置过期时间 expire key time(以秒为单位)--这是最常用的方式 setex(String key, int seconds, ...
- Realm Swift
Realm Swift 当前这个翻译,主要是方便我自己查阅api,有非常多地方写的比較晦涩或者没有翻译,敬请谅解 version 0.98.7 官方文档 參考文献 Realm支持类型 String,N ...