Home Web Front-end JS Tutorial Summary of javascript string functions_basic knowledge

Summary of javascript string functions_basic knowledge

May 16, 2016 pm 03:27 PM
javascript String functions

JS自带函数

concat

将两个或多个字符的文本组合起来,返回一个新的字符串。

var a = "hello";
var b = ",world";
var c = a.concat(b);
alert(c);
//c = "hello,world"

Copy after login

indexOf

返回字符串中一个子串第一处出现的索引(从左到右搜索)。如果没有匹配项,返回 -1 。

var index1 = a.indexOf("l");
//index1 = 2
var index2 = a.indexOf("l",3);
//index2 = 3
Copy after login

charAt

返回指定位置的字符。

var get_char = a.charAt(0);
//get_char = "h"
Copy after login

lastIndexOf

返回字符串中一个子串最后一处出现的索引(从右到左搜索),如果没有匹配项,返回 -1 。

var index1 = lastIndexOf('l');
//index1 = 3
var index2 = lastIndexOf('l',2)
//index2 = 2
Copy after login

match

检查一个字符串匹配一个正则表达式内容,如果么有匹配返回 null。

var re = new RegExp(/^\w+$/);
var is_alpha1 = a.match(re);
//is_alpha1 = "hello"
var is_alpha2 = b.match(re);
//is_alpha2 = null
Copy after login

substring

返回字符串的一个子串,传入参数是起始位置和结束位置。

var sub_string1 = a.substring(1);
//sub_string1 = "ello"
var sub_string2 = a.substring(1,4);
//sub_string2 = "ell"
Copy after login

substr

返回字符串的一个子串,传入参数是起始位置和长度

var sub_string1 = a.substr(1);
//sub_string1 = "ello"
var sub_string2 = a.substr(1,4);
//sub_string2 = "ello"
Copy after login

replace

用来查找匹配一个正则表达式的字符串,然后使用新字符串代替匹配的字符串。

var result1 = a.replace(re,"Hello");
//result1 = "Hello"
var result2 = b.replace(re,"Hello");
//result2 = ",world"
Copy after login

search

执行一个正则表达式匹配查找。如果查找成功,返回字符串中匹配的索引值。否则返回 -1 。

var index1 = a.search(re);
//index1 = 0
var index2 = b.search(re);
//index2 = -1
Copy after login

slice

提取字符串的一部分,并返回一个新字符串(与 substring 相同)。

var sub_string1 = a.slice(1);
//sub_string1 = "ello"
var sub_string2 = a.slice(1,4);
//sub_string2 = "ell"
Copy after login

split

通过将字符串划分成子串,将一个字符串做成一个字符串数组。

var arr1 = a.split("");
//arr1 = [h,e,l,l,o]
Copy after login

length

返回字符串的长度,所谓字符串的长度是指其包含的字符的个数。

var len = a.length();
//len = 5
Copy after login

toLowerCase

将整个字符串转成小写字母。

var lower_string = a.toLowerCase();
//lower_string = "hello"
Copy after login

toUpperCase

将整个字符串转成大写字母。

var upper_string = a.toUpperCase();
//upper_string = "HELLO"
Copy after login

字符串函数扩充

/*
===========================================
//去除左边的空格
===========================================

*/

String.prototype.LTrim = function()
{
return this.replace(/(^\s*)/g, "");
}
Copy after login


/*
===========================================
//去除右边的空格
===========================================
*/

String.prototype.Rtrim = function()
{
return this.replace(/(\s*$)/g, "");
}
Copy after login

/*
===========================================
//去除前后空格
===========================================
*/

String.prototype.Trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}
Copy after login

/*
===========================================
//得到左边的字符串
===========================================
*/

String.prototype.Left = function(len)
{

if(isNaN(len)||len==null)
{
len = this.length;
}
else
{
if(parseInt(len)<0||parseInt(len)>this.length)
{
len = this.length;
}
}

return this.substr(0,len);
}



Copy after login

/*
===========================================
//得到右边的字符串
===========================================
*/

String.prototype.Right = function(len)
{

if(isNaN(len)||len==null)
{
len = this.length;
}
else
{
if(parseInt(len)<0||parseInt(len)>this.length)
{
len = this.length;
}
}

return this.substring(this.length-len,this.length);
}



Copy after login

/*
===========================================
//得到中间的字符串,注意从0开始
===========================================
*/

String.prototype.Mid = function(start,len)
{
return this.substr(start,len);
}
Copy after login


/*
===========================================
//在字符串里查找另一字符串:位置从0开始
===========================================
*/

String.prototype.InStr = function(str)
{

if(str==null)
{
str = "";
}

return this.indexOf(str);
}

Copy after login

/*
===========================================
//在字符串里反向查找另一字符串:位置0开始
===========================================
*/

String.prototype.InStrRev = function(str)
{

if(str==null)
{
str = "";
}

return this.lastIndexOf(str);
}

Copy after login

/*
===========================================
//计算字符串打印长度
===========================================
*/

String.prototype.LengthW = function()
{
return this.replace(/[^\x00-\xff]/g,"**").length;
}
Copy after login

/*
===========================================
//是否是正确的IP地址
===========================================
*/

String.prototype.isIP = function()
{

var reSpaceCheck = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;

if (reSpaceCheck.test(this))
{
this.match(reSpaceCheck);
if (RegExp.$1 <= 255 && RegExp.$1 >= 0
&& RegExp.$2 <= 255 && RegExp.$2 >= 0
&& RegExp.$3 <= 255 && RegExp.$3 >= 0
&& RegExp.$4 <= 255 && RegExp.$4 >= 0)
{
return true;  
}
else
{
return false;
}
}
else
{
return false;
}

}

Copy after login


/*
===========================================
//是否是正确的长日期
===========================================
*/

String.prototype.isLongDate = function()
{
var r = this.replace(/(^\s*)|(\s*$)/g, "").match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
if(r==null)
{
return false;
}
var d = new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);

}

Copy after login

/*
===========================================
//是否是正确的短日期
===========================================
*/

String.prototype.isShortDate = function()
{
var r = this.replace(/(^\s*)|(\s*$)/g, "").match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if(r==null)
{
return false;
}
var d = new Date(r[1], r[3]-1, r[4]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}
Copy after login

/*
===========================================
//是否是正确的日期
===========================================
*/

String.prototype.isDate = function()
{
return this.isLongDate()||this.isShortDate();
}
Copy after login

/*
===========================================
//是否是手机
===========================================
*/

String.prototype.isMobile = function()
{
return /^0{0,1}13[0-9]{9}$/.test(this);
}
Copy after login

/*
===========================================
//是否是邮件
===========================================
*/

String.prototype.isEmail = function()
{
return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(this);
}
Copy after login

/*
===========================================
//是否是邮编(中国)
===========================================
*/

String.prototype.isZipCode = function()
{
return /^[\\d]{6}$/.test(this);
}

Copy after login

/*
===========================================
//是否是有汉字
===========================================
*/

String.prototype.existChinese = function()
{
//[\u4E00-\u9FA5]為漢字﹐[\uFE30-\uFFA0]為全角符號
return /^[\x00-\xff]*$/.test(this);
}
Copy after login

/*
===========================================
//是否是合法的文件名/目录名
===========================================
*/

String.prototype.isFileName = function()
{
return !/[\\\/\*\&#63;\|:"<>]/g.test(this);
}
Copy after login

/*
===========================================
//是否是有效链接
===========================================
*/

String.prototype.isUrl = function()
{
return /^http[s]&#63;:\/\/([\w-]+\.)+[\w-]+([\w-./&#63;%&=]*)&#63;$/i.test(this);
}



Copy after login

/*
===========================================
//是否是有效的身份证(中国)
===========================================
*/

String.prototype.isIDCard = function()
{
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;

}

Copy after login

/*
===========================================
//是否是有效的电话号码(中国)
===========================================
*/

String.prototype.isPhoneCall = function()
{
return /(^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)/.test(this);
}
Copy after login


/*
===========================================
//是否是数字
===========================================
*/

String.prototype.isNumeric = function(flag)
{
//验证是否是数字
if(isNaN(this))
{

return false;
}

switch(flag)
{

case null:    //数字
case "":
return true;
case "+":    //正数
return        /(^\+&#63;|^\d&#63;)\d*\.&#63;\d+$/.test(this);
case "-":    //负数
return        /^-\d*\.&#63;\d+$/.test(this);
case "i":    //整数
return        /(^-&#63;|^\+&#63;|\d)\d+$/.test(this);
case "+i":    //正整数
return        /(^\d+$)|(^\+&#63;\d+$)/.test(this);            
case "-i":    //负整数
return        /^[-]\d+$/.test(this);
case "f":    //浮点数
return        /(^-&#63;|^\+&#63;|^\d&#63;)\d*\.\d+$/.test(this);
case "+f":    //正浮点数
return        /(^\+&#63;|^\d&#63;)\d*\.\d+$/.test(this);            
case "-f":    //负浮点数
return        /^[-]\d*\.\d$/.test(this);        
default:    //缺省
return true;            
}
}

Copy after login

/*
===========================================
//是否是颜色(#FFFFFF形式)
===========================================
*/

String.prototype.IsColor = function()
{
var temp    = this;
if (temp=="") return true;
if (temp.length!=7) return false;
return (temp.search(/\#[a-fA-F0-9]{6}/) != -1);
}
Copy after login

/*
===========================================
//转换成全角
===========================================
*/

String.prototype.toCase = function()
{
var tmp = "";
for(var i=0;i<this.length;i++)
{
if(this.charCodeAt(i)>0&&this.charCodeAt(i)<255)
{
tmp += String.fromCharCode(this.charCodeAt(i)+65248);
}
else
{
tmp += String.fromCharCode(this.charCodeAt(i));
}
}
return tmp
}
Copy after login

/*
===========================================
//对字符串进行Html编码
===========================================
*/

String.prototype.toHtmlEncode = function()
{
var str = this;

str=str.replace(/&/g,"&");
str=str.replace(/</g,"<");
str=str.replace(/>/g,">");
str=str.replace(/\'/g,"&apos;");
str=str.replace(/\"/g,""");
str=str.replace(/\n/g,"<br>");
str=str.replace(/\ /g," ");
str=str.replace(/\t/g,"    ");

return str;
}

Copy after login

/*
===========================================
//转换成日期
===========================================
*/

String.prototype.toDate = function()
{
try
{
return new Date(this.replace(/-/g, "\/"));
}
catch(e)
{
return null;
}
}
Copy after login

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles