javascript 自定义常用方法
比如说页面的字符处理,js的正则表达式验证等等。下面我就将我自己浅薄的开发经验综合网上的庞杂资源稍稍综合整理一下,省得自己以后要用到时再搜索了。这个系列我会将平时常用的函数归纳整理起来,全当作是抛砖引玉吧。
Code is cheap.看代码:
一、常见的字符串处理函数
// 返回字符的长度,一个中文算2个
String.prototype.ChineseLength = function() {
return this .replace( / [ ^ \x00 - \xff] / g, " ** " ).length;
}
// 去掉字符串两端的空白字符
String.prototype.Trim = function() {
return this .replace( / ( ^ \s + ) | (\s + $) / g, "" );
}
// 去掉字符左端的的空白字符
String.prototype.LeftTrim = function() {
return this .replace( / ( ^ [\s] * ) / g, "" );
}
// 去掉字符右端的空白字符
String.prototype.RightTrim = function() {
return this .replace( / ([\s] * $) / g, "" );
}
/* 忽略大小写比较字符串是否相等
注:不忽略大小写比较用 == 号 */
String.prototype.IgnoreCaseEquals = function(str) {
return this .toLowerCase() == str.toLowerCase();
}
/* 不忽略大小写比较字符串是否相等 */
String.prototype.Equals = function(str) {
return ( this == str);
}
/* 比较字符串,根据结果返回 -1, 0
返回值 相同:0 不相同:-1
*/
String.prototype.CompareTo = function(str) {
if ( this == str) {
return 0 ;
} else
return - 1 ;
}
// 字符串替换
String.prototype.Replace = function(oldValue, newValue) {
var reg = new RegExp(oldValue, " g " );
return this .replace(reg, newValue);
}
// 检查是否以特定的字符串结束
String.prototype.EndsWith = function(str) {
return this .substr( this .length - str.length) == str;
}
// 判断字符串是否以指定的字符串开始
String.prototype.StartsWith = function(str) {
return this .substr( 0 , str.length) == str;
}
// 从左边截取n个字符
String.prototype.LeftSlice = function(n) {
return this .substr( 0 , n);
}
// 从右边截取n个字符
String.prototype.RightSlice = function(n) {
return this .substring( this .length - n);
}
// 统计指定字符出现的次数
String.prototype.Occurs = function(ch) {
// var re = eval("/[^"+ch+"]/g");
// return this.replace(re, "").length;
return this .split(ch).length - 1 ;
}
/* 构造特定样式的字符串,用 包含 */
String.prototype.Style = function(style) {
return " " , this , " " );
}
// 构造类似StringBuilder的函数(连接多个字符串时用到,很方便)
function StringBuilder(str) {
this .tempArr = new Array();
}
StringBuilder.prototype.Append = function(value) {
this .tempArr.push(value);
return this ;
}
StringBuilder.prototype.Clear = function() {
this .tempArr.length = 0 ;
}
StringBuilder.prototype.toString = function() {
return this .tempArr.join( '' );
}
// 字符串常见方法及扩展
function test() {
var testStr = " This is a test string " ;
var testStr2 = " 字符串 " ;
// alert(testStr.Trim());
// alert(testStr.LeftTrim());
// alert(testStr.RightTrim());
// alert(testStr2.ChineseLength());
// alert(testStr2.CompareTo(testStr));
// alert(testStr2.StartsWith("字符串"));
// document.write(testStr2.Style("color:red;width:100px"));
// alert(testStr2.LeftSlice(2));
// alert(testStr.RightSlice(7));
// alert(testStr.Occurs("s"));
/* StringBuilder测试 */
// var testStr3 = new StringBuilder("");
// testStr3.Append("test3\r\n");
// testStr3.Append("test3test3\r\n");
// testStr3.Append("test3");
// alert(testStr3.toString());
// testStr3.Clear();
// alert(testStr3.toString());
}
二、常用的正则表达式
/* -----------------------下面的函数还是涉及到了一些字符串的处理,但是当作正则表达式的一部分看起来更合理----------------------------- */
// 检查字符串是否由数字组成
String.prototype.IsDigit = function () {
var str = this .Trim();
return (str.replace( / \d / g, "" ).length == 0 );
}
// 校验字符串是否为浮点型
String.prototype.IsFloat = function () {
var str = this .Trim();
// 如果为空,则不通过校验
if (str == "" )
return false ;
// 如果是整数,则校验整数的有效性
if (str.indexOf( " . " ) == - 1 ) {
return str.IsDigit();
}
else {
if ( / ^(\-?)(\d+)(.{1})(\d+)$ / g.test(str))
return true ;
else
return false ;
}
}
// 检验是否是负整数
function isNegativeInteger(str) {
// 如果为空,则不通过校验
if (str == "" )
return false ;
if (str.IsDigit()) {
if (parseInt(str, 10 ) < 0 )
return true ;
else
return false ;
}
else
return false ;
}
// 检验是否是负浮点数数
function isNegativeFloat(str) {
// 如果为空,则不通过校验
if (str == "" )
return false ;
if (str.IsFloat()) {
if (parseFloat(str, 10 ) < 0 )
return true ;
else
return false ;
}
else
return false ;
}
// 是否是由字母组成的字符串
function isCharacter(str) {
return ( / ^[A-Za-z]+$ / .test(str));
}
// 是否是字母、数字组成的字符串
function isNumberCharacter(str) {
return ( / ^[A-Za-z0-9]+$ / .test(str));
}
// 是否是email
function isEmail(str) {
return ( / (\S)+[@]{1}(\S)+[.]{1}(\w)+ / .test(str))
}
// 是否是url(评注:网上流传的版本功能很有限,下面这个基本可以满足需求)
function isUrl(str) {
return ( / ([a-zA-z]+:\ / \ / )?[^s]* / .test(str));
}
// 是否是ip地址
function isIpAddress(str) {
return / (\d+)\.(\d+)\.(\d+)\.(\d+) / .test(str);
}
// 是否是汉字组成的字符串
function isChinese(str) {
return ( / ^[\u4e00-\u9fa5]+$ / .test(str));
}
// 是否是双字节字符(包括汉字在内)
function isUnicode(str) {
return ( / ^[\x00-\xff]+$ / .test(str));
}
// 是否是电话号码
function isTelephone(str) {
// 兼容格式: 国家代码(2到3位)-区号(2到3位)(-)?电话号码(7到8位)-分机号(3位)
return ( / ^(([0\+]\d{2,3}-)?(0\d{2,3}))?[-]?(\d{7,8})(-(\d{3,}))?$ / .test(str));
}
// 是否是手机号码
function isMobilePhone(str) {
return ( / ^((\(\d{3}\))|(\d{3}\-))?1[3,5]\d{9}$ / .test(str));
}
// 是否是QQ号码(腾讯QQ号从10000开始)
function isQQNumber(str) {
return ( / ^[1-9][0-9]{4,}$ / .test(str));
}
// 是否是国内的邮政编码(中国邮政编码为6位数字)
function isMailCode(str) {
return ( / \d{6} / .test(str));
}
// 是否是国内的身份证号码
function isIdNumber(str) {
return ( / \d{15}|\d{18} / .test(str));
}
关于正则表达式,网上还有很多的有深度的文章,我这里就拷贝几段常用的代码了,其实学懂了基本的正则知识后普通的验证不过是小菜一碟,不再赘述。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



An avatar on Netflix is a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

How to customize background image in Win11? In the newly released win11 system, there are many custom functions, but many friends do not know how to use these functions. Some friends think that the background image is relatively monotonous and want to customize the background image, but don’t know how to customize the background image. If you don’t know how to define the background image, the editor has compiled the steps to customize the background image in Win11 below. If you are interested If so, take a look below! Steps for customizing background images in Win11: 1. Click the win button on the desktop and click Settings in the pop-up menu, as shown in the figure. 2. Enter the settings menu and click Personalization, as shown in the figure. 3. Enter Personalization and click on Background, as shown in the picture. 4. Enter background settings and click to browse pictures

A Venn diagram is a diagram used to represent relationships between sets. To create a Venn diagram we will use matplotlib. Matplotlib is a commonly used data visualization library in Python for creating interactive charts and graphs. It is also used to create interactive images and charts. Matplotlib provides many functions to customize charts and graphs. In this tutorial, we will illustrate three examples to customize Venn diagrams. The Chinese translation of Example is: Example This is a simple example of creating the intersection of two Venn diagrams; first, we imported the necessary libraries and imported venns. Then we create the dataset as a Python set, after that we use the "venn2()" function to create

CakePHP is a powerful PHP framework that provides developers with many useful tools and features. One of them is pagination, which helps us divide large amounts of data into several pages, making browsing and manipulation easier. By default, CakePHP provides some basic pagination methods, but sometimes you may need to create some custom pagination methods. This article will show you how to create custom pagination in CakePHP. Step 1: Create a custom pagination class First, we need to create a custom pagination class. this

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

Vue is a popular JavaScript framework that provides many convenient functions and APIs to help developers build interactive front-end applications. With the release of Vue3, the render function has become an important update. This article will introduce the concept and purpose of the render function in Vue3 and how to use it to customize the rendering function. What is the render function? In Vue, template is the most commonly used rendering method, but in Vue3, you can use another method: r

The iOS 17 update for iPhone brings some big changes to Apple Music. This includes collaborating with other users on playlists, initiating music playback from different devices when using CarPlay, and more. One of these new features is the ability to use crossfades in Apple Music. This will allow you to transition seamlessly between tracks, which is a great feature when listening to multiple tracks. Crossfading helps improve the overall listening experience, ensuring you don't get startled or dropped out of the experience when the track changes. So if you want to make the most of this new feature, here's how to use it on your iPhone. How to Enable and Customize Crossfade for Apple Music You Need the Latest

How to implement custom middleware in CodeIgniter Introduction: In modern web development, middleware plays a vital role in applications. They can be used to perform some shared processing logic before or after the request reaches the controller. CodeIgniter, as a popular PHP framework, also supports the use of middleware. This article will introduce how to implement custom middleware in CodeIgniter and provide a simple code example. Middleware overview: Middleware is a kind of request
