JavaScript regular expressions and string RegExp and String (ii) _ Regular expressions

Source: Internet
Author: User
Tags arrays regular expression

In the previous article we introduced JavaScript regular expressions and string regexp and string (a), and this article continues to share relevant content.

Objective

I think that in the process of learning a programming language, strings, arrays, containers are very important parts, in order to improve the efficiency of programming, I usually to the strings, arrays and containers for in-depth learning, detailed understanding of the relevant features and corresponding APIs. This article is for JavaScript strings to learn to write down the notes, here with the need to share with friends.

Mind Mapping

How strings are Created

A string is one of the basic types in JavaScript, and its corresponding type is string, and you can create a string in two ways:

Create a basic type of string by assigning a value to a variable
Creating a String object by constructing a method (string)

Although two ways to create a different string representation, but in some scenarios, we need a string, but do not care whether it is a string base type or String object. In this scenario, a small change in the judgment of the string will occur.

The following code can be used to deepen understanding:

var s = ' ABCD1234DCBA '; Recommended way to create a string
var s1 = ' ABCD1234DCBA ';
var s2 = new String (s); Creates a string
var s3 = new String (s) by constructing a method;
Console.log (S===S1); True has attributes
Console.log (S===S2) of value types,//false base types and objects are unequal
console.log (S2===S3),//false different objects are
unequal Console.log (typeof s); String
console.log (typeof S2);//Object
//judge whether the input value is a base type string
function isstring (s) {return
 typeof s = = = ' String '
}
Console.log (isstring (s));//true
console.log (isstring (S2));//false
// Determines whether the input value is a string (basic type + string object form)
function isString2 (s) {return
 s!= null && typeof s.valueof () = = ' String ';
}
Console.log (IsString2 (s)); True
console.log (isString2 (S2));//true

Value invariant properties of strings

Strings are immutable in JavaScript. The so-called immutable means that when you generate a string and then invoke the string's API to manipulate the string, the original value of the string is not changed, and the result of the call processing is a new string.
The following code can be used to deepen understanding:

  var s = new String (' abc ');
  var r = s.touppercase ();
  alert (s);  ABC  s itself is not going to change
  alert (r);  ABC

Common APIs-string interception

No interception of strings, master the following three APIs:

Slice:String.slice (N1,N2) This is our commonly used string from the specified position (N1) to the specified position (N2);
Substring:String.substring (N1,N2) This is our commonly used string from the specified position (N1) to the specified position (N2);
Substr:String.substr (N1,N2) This is our usual string that intercepts the specified length (N2) from the specified location (N1);

Refer to the following code to deepen understanding:

var s = ' 0123456789 ';
var r1 = s.substring (1); 123456789 the second parameter defaults to character length
var r2 = s.substring (1,5); 1234
var r3 = s.substring (1); 123456789 the second parameter defaults to character length
var r4 = s.substring (1,5); 1234
var R5 = S.substr (1); 123456789 the second parameter defaults to character length
var r6 = s.substr (2,5); 23456
var R7 = s.substr (2,100); 23456789 The second argument is greater than the character length and is unaffected

Common APIs-string retrieval

For retrieval of strings, master the following three APIs. String retrieval is common in other programming languages, IndexOf and LastIndexOf two APIs, which are common in other programming languages and are relatively easy to understand. As for search, it is similar to indexof, except that its input parameter is not a retrieved string, but rather a regular expression that returns the index of the first occurrence of the regular expression.

Specific reference to the following code to deepen understanding:

var s = ' 0123abc401234 ';
Console.log (S.indexof (' 23 ')); 2
Console.log (S.lastindexof ('));//
Console.log (S.search (/[a-z]+/g));//4 retrieves the starting position of the occurrence of the character

Common APIs-string substitution

JS generally calls the Replace method to replace some characters in the string, which receives two parameters:
* The first parameter is used to describe the substring to be replaced, and the parameter type can be either a string or a regular expression. Note here, if it's a string, replaces the first matching substring in the original string, and if you do not set a regular expression that identifies ' G ', the result is the same if you want to replace all matched substrings, you must pass in a regular expression with identity g
* The second parameter is used to describe the replacement value. The parameter type can be a string, a function, or it can be a special sequence character (RegExp's static properties: −/&/'/'/1..n/$$, etc.).

The following code can be used to deepen understanding:

Code one. Basic matching operations

var s = ' Cat,bat,sat,fat ';
var res = s.replace (' at ', ' NE ');
Console.log (res);//cne,bat,sat,fat replaces only the first match
var res1 = s.replace (/at/, ' NE ');
Console.log (RES1); Cne,bat,sat,fat or just replace the first match
var res2 = s.replace (/at/g, ' NE ');
Console.log (Res2); Cne,bne,sne,fne Replace all matches

Code two. The second argument is a function

var s = ' ab<name>cd ';
Analog HTML Escapes < > with the
var res = s.replace (/[<>]/g,function (match,index,soustr) {
  switch (match) { C12/>case ' < ': return ' < ';
  Case ' > ': Return ' > '
  }
};
Console.log (RES); Ab&ltname&gtcd

Code three. Special sequence characters for flexible replacement

For character sou, the keyword key is expanded with {}
function strong (Sou,key) {
 var re = new RegExp (' (' +key+ ') ', ' G ');
 Return Sou.replace (Re, ' {$} '); The first capturing group
}
Console.log (Strong (S, ' at ')),//c{at},b{at},s{at},f{at}
//For character sou, the keyword key is enlarged
 with {} function Strong2 (sou,key) {
 var re = new RegExp (key, ' G ');
 Return Sou.replace (Re, ' {$&} '); $& matching string
 }
Console.log (Strong2 (S, ' at '));//c{at},b{at},s{at},f{at}

Common APIs-string grouping

In JS, the split method is used to group strings, which can receive two parameters:
* The first parameter represents a delimiter, either a string type or a RegExp object.
* The second parameter is optional, representing the number of receive groups, that is, the size of the result array returned. If you do not specify this argument, all groups are returned.
The following code can be used to deepen understanding:

var s = ' Cat,bat,sat,fat ';
var res = s.split (', ');
Console.log (RES); [' Cat ', ' bat ', ' sat ', ' fat ']
var res2 = S.split (/,/);
Console.log (Res2); [' Cat ', ' bat ', ' sat ', ' fat ']
var res3 = S.split (/,/,2);
Console.log (RES3); [' Cat ', ' bat '] returns only 2 groups

Common APIs-string matching

The match () method retrieves the string stringobject to find one or more text that matches the regexp. The behavior of this method depends to a great extent on whether the regexp has a sign G.

If RegExp does not have a flag G, then the match () method can only perform a match in Stringobject. If no matching text is found, match () returns NULL. Otherwise, it returns an array that holds information about the matching text it finds. The No. 0 element of the array holds the matching text, while the remaining elements hold the text that matches the subexpression of the regular expression. In addition to these regular array elements, the returned array also contains two object properties. The Index property declares the position of the starting character of the matching text in the Stringobject, and the input property declares a reference to the Stringobject.

If the regexp has a flag G, the match () method performs a global search and finds all the matching substrings in the stringobject. If no matching substring is found, NULL is returned. If one or more matching substrings are found, an array is returned. However, the contents of the array returned by the global match are very different from the former, and its array elements contain all the matching substrings in the stringobject, and there is no index attribute or input property.

Note: In global retrieval mode, match () does not provide information about the text that matches the subexpression, nor does it declare the position of each matching substring. If you need information for these global searches, you can use Regexp.exec ().

The following code can be used to deepen understanding:

var s = ' Cat,bat,sat,fat '; 
var reg =/[a-z] (at)/;
Console.log (S.match (reg)); [' Cat ', ' at ', index:0, input: ' Cat,bat,sat,fat ']
var res = S.match (/[a-z) (at)/g);
Console.log (RES); [' Cat ', ' bat ', ' sat ', ' fat ']

Common APIs-string comparisons

Two comparison methods, one is only greater than or less than the symbol, the other is the use of the Localecompare method, note that the method returns a number, the meaning of the number and other programming language comparison results are similar, not too much explanation. Related to the area involved, it is recommended to use Localecompare to compare strings.
The following code can be used to deepen understanding:

var S1 = ' abc ';
var s2 = ' BCD ';
var s3 = new String (' abc ');
Console.log (S1>S2); True
Console.log (S1==S3);//true compares S1 with s3.tostring () Console.log (S1.localecompare
(S2));//-1 S1 less than S2
Console.log (S1.localecompare (S3));//0 S1 value is equal to S3

These are the JavaScript regular expressions and string regexp and Strings (ii) that are shared by this article, and I hope you'll like it.

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.