Javascript Regular Expression and String RegExp and String (2), regular expression regexp
In the previous article, we introduced javascript Regular Expressions and strings RegExp and String (1). This article will continue to share with you.
Preface
In my opinion, strings, arrays, and containers are very important in learning a programming language. To improve programming efficiency, I usually study strings, arrays, and containers in depth to learn more about relevant features and related APIs. This article is a note written for javascript string learning and shared with friends who need it.
Mind Map
String Creation Method
A String is one of the basic types in javascript. It corresponds to a String. You can create a String in two ways:
Creates the basic string type by assigning values to variables.
Create a String object through the constructor (String)
Although the two methods create different string representations, in some scenarios, we need a string, but do not care whether it is a basic string type or a String object. In this scenario, the judgment of the string changes a little.
For more information, see the following code:
Var s = 'abcd1234dcba '; // The recommended String creation method is var s1 = 'abcd1234dcba'; var s2 = new String (s ); // create the String var s3 = new String (s); console by using the constructor. log (s = s1); // true has a value type feature console. log (s = s2); // false the basic type and object are not equal to the console. log (s2 = s3); // false different objects are not equal to the console. log (typeof s); // stringconsole. log (typeof s2); // object // judge whether the input value is of the basic type. function isString (s) {return typeof s === 'string'} console. log (isString (s); // truec Onsole. log (isString (s2); // false // judge 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); // trueconsole. log (isString2 (s2); // true
Character string value unchanged
The string is unchangeable in Javascript. The so-called immutable means that when you generate a string and then call the API of the string to operate on the string, the original value of the string will not change, the result of the call processing is a new string.
See the following code to learn more:
Var s = new String ('abc'); var r = s. toUpperCase (); alert (s); // abc s itself is not changing alert (r); // ABC
Common API-string Truncation
If you do not want to intercept strings, you can use the following three APIs:
Slice: String. slice (N1, N2) is a commonly used String from the specified position (N1) to the specified position (N2;
Substring: String. substring (N1, N2), which is a commonly used String from the specified position (N1) to the specified position (N2;
Substr: String. substr (N1, N2) This is a commonly used String to extract the specified length (N2) from the specified position (N1;
Refer to the following code for better understanding:
Var s = '20140901 ';
Var r1 = s. substring (1); // The second parameter of 123456789 defaults to the character length.
Var r2 = s. substring (1, 5); // 1234
Var r3 = s. substring (1); // The second parameter of 123456789 defaults to the character length.
Var r4 = s. substring (1, 5); // 1234
Var r5 = s. substr (1); // The second parameter of 123456789 defaults to the character length.
Var r6 = s. substr (2, 5); // 23456
Var r7 = s. substr (2,100); // The second parameter of 23456789 is greater than the character length and is not affected.
Common API-string SEARCH
For string search operations, you can master the following three APIs. String retrieval is common in other programming languages. indexOf and lastIndexOf APIs are common in other programming languages and easy to understand. Search is similar to indexOf, but its input parameter is not a string to be searched, but a regular expression. The return value is the index of the first matching item of the regular expression.
For more information, see the following code:
Var s = '0123abc401234 '; console. log (s. indexOf ('23'); // 2console. log (s. lastIndexOf ('23'); // 10console. log (s. search (/[a-z] +/g); // 4 search for the starting position of the character
Common API-string replacement
In JS, the replace method is generally called to replace certain characters in the string. This method receives two parameters:
* The first parameter is used to describe the substring to be replaced. The parameter type can be a string or a regular expression. Note that if it is a string, it will only Replace the first matched substring in the original string, and if it is a regular expression that does not specify 'G, the same result is obtained after replacement. If you want to replace all matched substrings, you must pass in a regular expression with the ID g.
* The second parameter is used to describe the replacement value. The parameter type can be a string, a function, or a static attribute containing special sequence characters (RegExp: −/ &/'/1 .. n/$, etc ).
For more information, see the following code:
Code 1. Basic matching operations
Var s = 'cat, bat, sat, fat'; var res = s. replace ('at', 'ne '); console. log (res); // cNE, bat, sat, and fat replace only the first matching item var res1 = s. replace (/at/, 'ne '); console. log (res1); // cNE, bat, sat, and fat should only Replace the first matching item var res2 = s. replace (/at/g, 'ne '); console. log (res2); // replace all matching items with cNE, bNE, sNE, and fNE
Code 2. The second parameter is the function.
Var s = 'AB <name> Cd'; // simulate HTML to escape var res = s. replace (/[<>]/g, function (match, index, souStr) {switch (match) {case '<': return '<'; case '> ': return '>' ;}}); console. log (res); // AB & ltname & gtcd
Code 3. Flexible replacement of special sequence characters
// For the sou character, use {} to expand the keyword key to function strong (sou, key) {var re = new RegExp ('+ key + ')', 'G'); return sou. replace (re, '{$1}'); // $1 first capture group} console. log (strong (s, 'at'); // c {at}, B {at}, s {at}, f {at} // For sou characters, expand the keyword key with {} function strong2 (sou, key) {var re = new RegExp (key, 'G'); return sou. replace (re, '{$ &}'); // $ & matched string} console. log (strong2 (s, 'at'); // c {at}, B {at}, s {at}, f {}
Common API-string grouping
JS uses the split method to group strings. This method can receive two parameters:
* The first parameter indicates the delimiter, which can be a string or RegExp object.
* The second parameter is optional, indicating the number of receiving groups, that is, the size and size of the returned result array. If this parameter is not specified, all groups are returned.
For more information, see the following code:
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'] only two groups are returned.
Common API-String Matching
The match () method retrieves the stringObject string to find one or more texts that match regexp. The behavior of this method depends largely on whether regexp has a flag.
If regexp does not mark g, the match () method can only perform one match in stringObject. If no matching text is found, match () returns null. Otherwise, it returns an array containing information related to the matched text it finds. The 0th elements in the array store the matching text, while the remaining elements store the text that matches the regular expression's subexpression. In addition to these regular array elements, the returned array also contains two object attributes. The index attribute declares the position of the starting character of the matching text in the stringObject, And the input attribute declares the reference to the stringObject.
If regexp has a flag, the match () method performs a global search and finds all matching substrings in stringObject. If no matched substring is found, null is returned. If one or more matched substrings are found, an array is returned. However, the content of the array returned by global match is very different from that returned by the former. Its array elements store all matched substrings in stringObject, and there is no index or input attribute.
Note: In global search mode, match () does not provide text information that matches the subexpression, nor declare the position of each matched substring. You can use RegExp.exe c () to retrieve global information ().
For more information, see the following code:
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 API-string comparison
There are two comparison methods: one is greater than or less than the symbol, and the other is the localeCompare method. Note that the return value of this method is a number, the meanings of numbers are similar to those in other programming languages. We recommend that you use localeCompare to compare the strings.
For more information, see the following code:
Var s1 = 'abc'; var s2 = 'bcd'; var s3 = new String ('abc'); console. log (s1> s2); // trueconsole. log (s1 = s3); // true compares s1 with s3.toString. log (s1.localeCompare (s2); //-1 s1 is smaller than s2console. log (s1.localeCompare (s3); // The value of 0 s1 is equal to that of s3
The above content is the javascript Regular Expression and String RegExp and String (2) shared in this article.