Analysis of string common methods of JavaScript language essence

Source: Internet
Author: User

JavaScript language essence of string common method analysis 1. String Common Method Analysis 1.1 String.prototype.slice ()

The slice (start,end) method copies part of a string to construct a new string

When start<0, it will be added to String.Length

The end parameter is optional and the default value is String.Length. If end<0, it will be added to String.Length

var text= ' and in it he say "any damn fool could '; var a=text.slice (+); // A is ' "any damn fool could ' var b = Text.slice (0,3); // b is ' and ' var c = text.slice ( -5); // c is ' could '
1.2 String.prototype.substring ()

Substring method cannot handle negative parameters

JavaScript language essence authors do not recommend the use of substring, recommended with slice

For substring (), slice (), substr (), there is a detailed comparison of this article

Http://www.cnblogs.com/ider/p/js-slice-vs-substr-vs-substring-table.html

Take a look at the conclusions in the article

The main differences between the three methods are as follows:
1. The parameter 1 of the three methods represent the starting position of the substring, and parameter 2 represents the end position in slice and substring, while the substring length is represented in the substr;
2. For negative attitude, when it appears in the position of parameter 1, slice and substr from the end of the calculation, and substring does not support the end count method is directly regarded as 0; when it appears in the parameter 2 position, slice and substring are treated with parameter 1: The former is calculated from the end, The latter is converted to 0, whereas the substr returns an empty string with a negative length of 0;
3. For the case that parameter 1 is greater than the parameter 2, the substring is the biggest difference is that it will exchange two parameters and then intercept the substring, substr because the second parameter is the length so that there is no exception, slice ozone still normal search for the substring of the beginning and end of the position, if the start position after the tail of the return empty string.

1.3 String.prototype.match ()

The String.match method matches a string and a regular expression. It determines how the match is based on the G-ID, and if there is no G-ID, the String.match (regexp) and the call Regexp.exec (string) are the same results. If there is a G ID, it returns an array that contains all the matches except the capturing packet. Note that the capture group does not contain the.

var text= ' ; var tags=/[^<>]+|< (\/?) ([a-za-z]+) ([^<>]*) >/g; var a=Text.match (tags), a=["

String.match and Regexp.exec differences

varSometext= "web2.0. net2.0";varpattern=/(\w+) (\d) \. (\d)/G;varOutcome_exec=pattern.exec (sometext);varOutcome_matc=Sometext.match (pattern);//outcome_exec:["web2.0", "Web", "2", "0"]//outcome_matc:["web2.0", "net2.0"]varSometext= "web2.0. net2.0";varpattern=/(\w+) (\d) \. (\d)/;//with no GvarOutcome_exec=pattern.exec (sometext);varOutcome_matc=Sometext.match (pattern);//outcome_exec: ["web2.0", "Web", "2", "0"]//OUTCOME_MATC: ["web2.0", "Web", "2", "0"]

1) Exec is the RegExp object method, and match is a string object method;

2) If no results are found, both return null;

3) match can return all matches only if the regular expression must specify the global G property, otherwise the match is equivalent to the result of the Exec method;

4) Exec always returns information related to the first match, whose return array the first value is the first matched string, and the rest is the inverse reference of all the groupings (that is, the matching content of the parentheses);

5) Exec after setting the G property, although the match result is not affected by G, the returned result is still an array (the first value is the first match to the string, the later is the grouping match), but will change the value of index and lastindex, etc. Sets the starting position of the object's match to the character position immediately following the string, and when exec is called the second time, it is retrieved from the character position indicated by lastindex. The same match method, after setting the G property, also changes the value of index and lastindex, but is one-time. It is not possible to accumulate in a process like exec (the result is placed in the Matches collection), so it is not possible to accumulate the next retrieved location.

1.4 String.prototype.replace

The Replace (Searchvalue,replacevalue) method finds and replaces a string and returns a new string.

When Searchvalue is a string, Searchvalue is replaced only where it first appears

var result= "Mother_in_law". Replace (' _ ', '-'); result= "Mother-in_law";

When Searchvalue is a regular expression and has a G-ID, it replaces all matches, and if there is no G-ID, only the first match is replaced

var oldareacode=/\ ((\d{3}) \)/g; var p= ' (555) 666-(121) 2 '. Replace (Oldareacode, ' $1-'= "555-666-121-2";

When Replacevalue is a function, this method calls it for each match and uses the string returned by the function as the replacement text.

var p= "1a1c". Replace (/\d/g,function() {    return ' X ';}); P= "XAXC";

If the Replacevalue function requires more complex processing logic, you can pass in parameters for the function, the first parameter is the entire matched text, the second parameter is the text captured in Group 1, the second parameter is the text captured by grouping 2, and so on

// capitalize the first letter of all the words in a sentence var result= "Hello World". Replace (/(\w) \w*\b/g,function(A, b    ) {return B.touppercase () +a.slice (1);}); Result= "Hello World"

A simple HTML escape method in the book

string.prototype.entityify=function(){    varCharacter={        ' < ': ' &lt; ',        ' > ': ' &gt; ',        ' & ': ' &amp; ',        ' "': ' &quot; '    }; return function(){        return  This. replace (/[<>& "]/g,function(c) {returnCharacter[c];    }); };} (); Alert ("<&>". Entityify ());//&lt;&amp;&gt;
1.5 String.prototype.split ()

The String.Split (Separator,limit) method splits a string into fragments to create an array of strings.

The optional parameter limit limits the number of fragments to be segmented. The separator parameter can be a string or a regular expression

If separator is an empty string, an array of single characters is returned:

var digits= ' 0123456789 '; var a=digits.split (', 5); a=["0", "1", "2", "3", "4"]

If separator is not empty, split will find where all the separator appear

var c = ' a|b|c| '. Split (' | ' c=[' A ', ' B ', ' C ', '];

If the split argument is a regular expression

var text= ' Last, first     , Middle '; var res=text.split (/\s*,\s*/), res=["Last", "first", "Middle"]

If the split argument is a regular expression, the text from the capturing group is included in the segmented array

var text= ' Last, first     , Middle '; var res=text.split (/\s* (,) \s*/), res=["Last", ",", "first", ",", "middle"]
1.6 String.prototype.search ()

The search method is similar to the IndexOf method, except that it accepts a regular expression as a parameter instead of a string

If a match is found, it returns the first character position that matches, and returns 1 if no match is found.

Analysis of string common methods of JavaScript language essence

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.