Encyclopedia of string manipulation functions in JavaScript (including regular)

Source: Internet
Author: User
Tags dateformat getdate trim valid


*
******************************************
JS Self-band function
******************************************
*/

Concat
Combines the text of two or more characters to return a new string.
var a = "Hello";
var B = ", World";
var C = A.concat (b);
alert (c);
c = "Hello,world"

IndexOf
Returns the index (search from left to right) of the first occurrence of a substring in a string. If there is no match, return-1.
var index1 = A.indexof ("L");
INDEX1 = 2
var index2 = A.indexof ("L", 3);
INDEX2 = 3

CharAt
Returns the character at the specified position.
var Get_char = A.charat (0);
Get_char = "H"

LastIndexOf
Returns the index (search from right to left) of the last occurrence of a substring in a string, or 1 if there are no matches.
var index1 = LastIndexOf (' l ');
INDEX1 = 3
var index2 = LastIndexOf (' l ', 2)
Index2 = 2
Match
Checks that a string matches the content of a regular expression, if no match returns NULL.
var re = new RegExp (/^w+$/);
var is_alpha1 = A.match (re);
IS_ALPHA1 = "Hello"
var is_alpha2 = B.match (re);
IS_ALPHA2 = null

Substring
Returns a substring of a string in which the incoming argument is the starting and ending position.
var sub_string1 = a.substring (1);
Sub_string1 = "Ello"
var sub_string2 = a.substring (1,4);
Sub_string2 = "ell"

Substr
Returns a substring of a string in which the incoming argument is the starting position and length
var sub_string1 = a.substr (1);
Sub_string1 = "Ello"
var sub_string2 = a.substr (1,4);
Sub_string2 = "Ello"

Replace
Used to find a string that matches a regular expression, and then use a new string instead of a matching string.
var result1 = A.replace (Re, "Hello");
RESULT1 = "Hello"
var result2 = B.replace (Re, "Hello");
RESULT2 = ", World"

Search
Performs a regular expression-matching lookup. Returns the matching index value in the string if the lookup succeeds. otherwise return-1.
var index1 = A.search (re);
index1 = 0
var index2 = B.search (re);
Index2 =-1

Slice
Extracts part of the string and returns a new string (same as substring).
var sub_string1 = A.slice (1);
Sub_string1 = "Ello"
var sub_string2 = A.slice (1,4);
Sub_string2 = "ell"

Split
Make a string an array of strings by dividing the strings into substrings.
var arr1 = A.split ("");
ARR1 = [H,e,l,l,o]

Length
Returns the length of a string, called the length of a string, that is the number of characters it contains.
var len = A.length ();
Len = 5

toLowerCase
Converts the entire string into lowercase letters.
var lower_string = A.tolowercase ();
lower_string = "Hello"

toUpperCase
Converts the entire string to uppercase.
var upper_string = A.touppercase ();
upper_string = "HELLO"

/*
******************************************
String function expansion
******************************************
*/

/*
===========================================
Remove the left space
===========================================

*/
String.prototype.LTrim = function ()
{
Return This.replace (/(^s*)/g, "");
}

/*
===========================================
Remove the space on the right
===========================================
*/
String.prototype.Rtrim = function ()
{
Return This.replace (/(s*$)/g, "");
}

/*
===========================================
Remove space before and after
===========================================
*/
String.prototype.Trim = function ()
{
Return This.replace (/(^s*) | ( s*$)/g, "");
}

/*
===========================================
Get the string on the left
===========================================
*/
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);
}


/*
===========================================
Get the string on the right
===========================================
*/
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);
}

/*
===========================================
Get the middle string, note starting from 0
===========================================
*/
String.prototype.Mid = function (Start,len)
{
Return This.substr (Start,len);
}

/*
===========================================
Find another string in a string: position starting from 0
===========================================
*/
STRING.PROTOTYPE.INSTR = function (str)
{

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

return This.indexof (str);
}

/*
===========================================
To reverse find another string in a string: position 0 start
===========================================
*/
String.prototype.InStrRev = function (str)
{

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

return This.lastindexof (str);
}

/*
===========================================
Calculate string Print length
===========================================
*/
String.prototype.LengthW = function ()
{
Return This.replace (/[^x00-xff]/g, "* *"). Length;
}

/*
===========================================
is the correct IP address
===========================================
*/
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;
}

}

/*
===========================================
Whether it's the right long date
===========================================
*/
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]);

}

/*
===========================================
Whether it's the right short date
===========================================
*/
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]);
}

/*
===========================================
is the correct date
===========================================
*/
String.prototype.isDate = function ()
{
Return this.islongdate () | | This.isshortdate ();
}

/*
===========================================
Whether it is a mobile phone
===========================================
*/
String.prototype.isMobile = function ()
{
Return/^0{0,1}13[0-9]{9}$/.test (this);
}

/*
===========================================
Whether it is a message
===========================================
*/
String.prototype.isEmail = function ()
{
Return/^w+ (-w+) | (. w+)) *@[a-za-z0-9]+ ((. | -) [a-za-z0-9]+] *. [A-za-z0-9]+$/.test (this);
}

/*
===========================================
is postcode (China)
===========================================
*/

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

/*
===========================================
Whether there is a Chinese character
===========================================
*/
String.prototype.existChinese = function ()
{
[U4e00-u9fa5]?? H word? [Ufe30-uffa0] Jin owe??
Return/^[x00-xff]*$/.test (this);
}

/*
===========================================
is the legal filename/directory Name
===========================================
*/
String.prototype.isFileName = function ()
{
return!/[\/*?|: "<>]/g.test (this);
}

/*
===========================================
Whether it is a valid link
===========================================
*/
STRING.PROTOTYPE.ISURL = function ()
{
Return/^http[s]?:/ /([w-]+.) +[w-]+ ([w-./?%&=]*)? $/i.test (this);
}

/*
===========================================
is the valid ID card (China)
===========================================
*/
String.prototype.isIDCard = function ()
{
var isum=0;
var info= "";
var sId = this;

var acity={11: "Beijing", 12: "Tianjin", 13: "Hebei", 14: "Shanxi", 15: "Inner Mongolia", 21: "Liaoning", 22: "Jilin", 23: "Heilongjiang", 31: "Shanghai", 32: "Jiangsu", 33: "Zhejiang", 34: "Anhui", 35 : "Fujian", 36: "Jiangxi", 37: "Shandong", 41: "Henan", 42: "Hubei", 43: "Hunan", 44: "Guangdong", 45: "Guangxi", 46: "Hainan", 50: "Chongqing", 51: "Sichuan", 52: "Guizhou", 53: "Yunnan", 54: "Tibet", 61: "Shaanxi", 62: "Gansu", 63: "Qinghai", 64: "Ningxia", 65: "Xinjiang", 71: "Taiwan", 81: "Hong Kong", 82: "Macao", 91: "Foreign"};

if (!/^d{17} (d|x) $/i.test (sId))
{
return false;
}
Sid=sid.replace (/x$/i, "a");
Illegal areas
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, "/")

Illegal birthday
if (sbirthday!= (d.getfullyear () + "-" + (D.getmonth () +1) + "-" + d.getdate ())
{
return false;
}
for (var i = 17;i>=0;i–)
{
Isum + + (Math.pow (2,i)%) * parseint (Sid.charat (17–i), 11);
}

if (isum%11!=1)
{
return false;
}
return true;

}

/*
===========================================
is a valid phone number (China)
===========================================
*/
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);
}

/*
===========================================
Whether it is a number
===========================================
*/
String.prototype.isNumeric = function (flag)
{
Verify that you are a number
if (isNaN (this))
{

return false;
}

Switch (flag)
{

Case NULL://number
Case "":
return true;
Case "+"://Positive
Return/(^+?| ^d?) d*.? D+$/.test (this);
Case "-"://Negative
Return/^-d*.? D+$/.test (this);
Case "I"://Integer
Return/(^-?| ^+?| d) D+$/.test (this);
Case "+i"://Positive integer
return/(^d+$) | (^+?d+$)/.test (this);
Case "I"://Negative integer
Return/^[-]d+$/.test (this);
Case "F"://floating-point number
Return/(^-?| ^+?| ^d?) D*.d+$/.test (this);
Case "+f"://Positive floating-point number
Return/(^+?| ^d?) D*.d+$/.test (this);
Case "F"://Negative floating-point number
Return/^[-]d*.d$/.test (this);
Default://Defaults
return true;
}
}

/*
===========================================
Whether it is a color (#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);
}

/*
===========================================
Convert Perfect angle
===========================================
*/
String.prototype.toCase = function ()
{
var tmp = "";
for (Var i=0;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
}

/*
===========================================
HTML Encoding A string
===========================================
*/
String.prototype.toHtmlEncode = function ()
{
var str = this;

Str=str.replace (/&/g, "&");
Str=str.replace (/Str=str.replace (/>/g, ">");
Str=str.replace (/'/g, "&apos;");
Str=str.replace (/"/g," "");
Str=str.replace (/n/g, "
“);
Str=str.replace (//g, "");
Str=str.replace (/t/g, "");

return str;
}

/*
===========================================
Convert to date
===========================================
*/
String.prototype.toDate = function ()
{
Try
{
return new Date (This.replace (/-/g, "/"));
}
catch (E)
{
return null;
}
}

1.ASC (x), CHR (x): convert character, character code

2. Filter: Searching for a specific string in a string array

Format: V=filter (X,s[,include[,compare]])

Instance:

Dim x () ={"Kjwang", "wangkj", "Peter"}

Dim V

V=filter (x, "kj") ' Result V (0) = "Kjwang", V (1) = "WANGKJ"

V=filter (x, "KJ", false) ' result V (0) = "Peter"

V=filter (x, "kj", True,vbtextcompare) ' Search by case

3.InStr: Looking for string position (InStrRev: Upside down for string)

Format:

V=instr (x,y) ' to find the position of the Y string from the 1th character of the x string

V=instr (n,x,y) ' to find the position of the Y string from the nth character of the X string

Format:

V=instrrev (X,s[,n[,compare]])

4. Join: Connecting a string

Format: V=join (X[,d]) ' d as separator character

5. Len (x): Calculates the length of the string x

Format: V=len (x)

6.Left (X,n): Returns the string x left n characters (corresponding to right (X,n))

7. Mid: Reading characters in the middle of a string X

Format: V=mid (x,n,m)

8. LTrim (x), Rtim (x), Trim (x) White-space character

9.Replace: String substitution

Format: V=replace (X,S,R)

Example: x= "I saw a saw a saw"

V=replace (x, "saw", "so") ' v= ' L so "a"

10.Split: String Segmentation

Format: V=split (S[,d])

Example: V=split ("Vb.net,iis6.0,asp.net", ",")

' Result V (0) = "vb.net", V (1) = "Iis6.0″,v (2) =" asp.net "

11.StrReverse: Reverse String

Example: V=strreverse ("Kjwang") ' v= ' GNAWJK

12.UCase (x), LCase (x): Changing the case of English letters

Example: x= "HELLO,VB Chinese!"

V=ucase (x) ' v= ' HELLO,VB Chinese! ”
1. Take out date Time

-1) DateValue (x), TimeValue (x)

Format: V=datevalue (x): Removed "date" section

V=timevalue (x) ' class

-2) year (x), Month (x), day (x)

Format: v=year (x)

V=month (x)

V=day (x)

Hour (x), Minute (x), Second (x): When taken out, minutes, seconds

-3) DateSerial (y,m,d): Date of merging year, month and day

Instance: Dim V

V=dateserial (1996,10,5) ' V=1996/10/5

TimeSerial (H,m,s): Time of merging, minutes, seconds

2.Now: Read system date Time

Format: V=now

3.Timer: The number of seconds elapsed since the early morning 12:00:00am

Format: V=timer

4.DatePart (p,x): Take out the values of each part of the year, month, day, etc.

Example: Dim x= #2/10/1996 16:45:30#

V=datepart ("yyyy", X) ' v=1996 year

V=datepart ("M", X) ' v=2 month

V=datepart ("D", X) ' V=10 Day

V=datepart ("H", X) ' v=16

V=datepart ("n", X) ' v=45

V=datepart ("s", X) ' v=30 seconds

V=datepart ("Q", X) ' v=1 season (first season, spring)

V=datepart ("Y", X) ' V=41 Day (41st Day of 1996)

V=datepart ("ww", X) ' V=6 Week (6th week of 1996)

V=datepart ("W", X) ' V=7 (7th Day of 6th Week, Saturday)

5. DATEADD (p,n,x): Add and subtract the new date time after some time

Format: V=dateadd (p,n,x) ' p value ibid.: "yyyy", "M", etc.

Example: Dim x= #1/31/1996 16:45:30#

V=dateadd ("yyyy", -3,x) ' minus 3 years, V=1993/1/31 16:45:30

6.DateDiff (P,X1,X2): Calculates the difference ' p value of two datetime times

Example: Dim x1= #12/31/1996 16:45:30#

x2= #2/10/1997 9:30:50#

V=datediff ("yyyy", x1,x2) ' V=1 year

7. FormatDateTime: Format of date Time

Format: V=formatdateyime (x[, date format))

Date format values: Dateformat.generaldate, Dateformat.longdate,

Datefotmat.shortdate, Dateformat.longtime, Dateformat.shorttime

8.MonthName: Returns the name of the month

Example: V=monthname (5) ' v= ' May '

9.WeekDayName: Return week name ' usage same as 8.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.