Analysis of Match,charat,charcodeat,map,search usage in common knotty points of JS

Source: Internet
Author: User
Tags md5 md5 encryption regular expression sha1 square root tostring

The example of this article tells the match,charat,charcodeat,map,search usage of JS common difficult point analysis. Share to everyone for your reference, specific as follows:

JavaScript Match () method

Definitions and usage

The match () method retrieves the specified value within a string, or finds a match for one or more regular expressions.

The method is similar to IndexOf () and LastIndexOf (), but it returns the specified value, not the position of the string.

Grammar

Matches a string that returns the specified value

Stringobject.match (Searchvalue)

Matches regular, returns the specified value

Stringobject.match (RegExp)

Use Match () to retrieve a string example:

<body>

<script type= "Text/javascript" >

Varstr= "Hello world!"

document.write (Str.match ("World") + "<br/>")

document.write (Str.match ("World") + "<br/>")

document.write (Str.match ("worlld") + "<br/>")

document.write (Str.match ("world!"))

</script>

</body>

The result of the final appearance is, world,null,null,world!

Use Match () to retrieve a matching example of a regular expression:

<body>

<script type= "Text/javascript" >

Varstr= "1 plus 2 equal 3";

The regular expression here must be coupled with G, a global match, or it will match a value that returns

document.write (Str.match (/\d+/g))

</script>

</body>

In general, we use match on the top of the more, you can use it to proxy indexof and LastIndexOf to determine whether there is a value in the string.

JavaScript Search () method

Definitions and usage

The search () method retrieves the substring specified in the string, retrieves the substring that matches the regular expression, retrieves the starting position of the returned matching substring, cannot retrieve the value, and returns-1.

Grammar

Stringobject.search (RegExp)

This parameter can be a substring that needs to be retrieved in Stringobject, or it can be a RegExp object that needs to be retrieved.

To perform a retrieval that ignores case, append the flag I.

Search () Example:

<script type= "Text/javascript" >

Varstr= "Visit w3school!"

document.write (Str.search (/w3school/))

</script>

Returns the index value of 6,search is usually used in conjunction with the regular, you can achieve the effect of indexof.

JavaScript charAt () method

Definitions and usage

The CharAt () method returns the character at the specified position.

Note that JavaScript does not have a character data type that is different from a string type, so the character returned is a string of length 1.

Grammar

Returns the string at the specified position

Stringobject.charat (Index)

Chartat instance:

<script type= "Text/javascript" >

Varstr= "Hello world!"

document.write (Str.charat (1))

</script>

The final return result is: E, usually we can get a specific character from a string by Chartat.

JavaScript charCodeAt () method

Definitions and usage

The charCodeAt () method returns the Unicode encoding of the character at the specified position. This return value is an integer between 0-65535.

The method charCodeAt () is similar to the operation performed by the CharAt () method, except that the former returns the encoding of the character at the specified position, and the latter returns a string of characters subcode.

Grammar

Stringobject.charcodeat (Index)

charCodeAt () instance

Note: The subscript for the first character in the string is 0. If index is a negative number, or is greater than or equal to the length of the string, charCodeAt () returns NaN.

<script type= "Text/javascript" >

Varstr= "Hello world!"

document.write (Str.charcodeat (1))

Returns the Unicode encoding of H 101

</script>

Array.prototype.map () method in JS

Definitions and usage

The map () method returns a new array of return values that are composed of each element in the original array calling a specified method.

Grammar

Array.map (callback[, Thisarg])

Callback the elements in the original array after the method returns a new element.

The first parameter of the Currentvalue,callback, the element currently being passed in the array.

The second parameter of the Index,callback, the index of the element currently being passed in the array.

The third parameter of the Array,callback, which invokes an array of the map methods.

Thisarg the object that this point is when the callback function is executed.

The map method invokes the callback function in order for each element in the original array. Callback the return value after each execution is grouped together to form a new array. The callback function is invoked only on a valued index, which has never been assigned a value or used

The index deleted by delete is not invoked. The callback function is automatically passed in three parameters: an array element, an element index, and the original array itself.

First example of using map ():

The following code converts all the words in an array to the corresponding plural form.

Functionfuzzyplural (single) {

Varresult = Single.replace (/o/g, ' e ');

if (single = = ' Kangaroo ') {

result = = ' SE ';

}

Returnresult;

}

Varwords = ["Foot", "Goose", "Moose", "kangaroo"];

Console.log (Words.map (fuzzyplural));

Final results:

["Feet", "geese", "Meese", "Kangareese"]

To find the square root example of each element in an array

Varnumbers = [1, 4, 9];

Varroots = Numbers.map (MATH.SQRT);

/* Roots value is [1, 2, 3], the value of numbers is still [1, 4, 9] * *

Using the Map method on a string

Varmap = Array.prototype.map

Vara = Map.call ("Hello World", function (x) {returnx.charcodeat (0);})

The values for a are [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

<! DOCTYPE html>

<meta charset= "UTF-8" >

<title></title>

<body>

<script type= "Text/javascript" >

var map = Array.prototype.map

Vara = Array.prototype.map.call ("Hello World", function (x) {returnx.charcodeat (0);})

The values for a are [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

alert (a);

</script>

</body>

Map compatible with old environment

A map is a newly added method in the most recent ECMA-262 standard, so some older browsers might not implement the method. In browsers that do not natively support the map method, you can use the following Javascript code to implement it. The algorithm used is ECMA-262, 5th edition. Suppose object, TypeError, and Array have their original values. And the original value of Callback.call is also Function.prototype.call.

Realize ECMA-262, Edition 5, 15.4.4.19

Reference: http://es5.github.com/#x15.4.4.19

if (! Array.prototype.map) {

Array.prototype.map =function (callback, Thisarg) {

Vart, A, K;

if (this==null) {

Thrownewtypeerror ("This is null or not defined");

}

1. Assign o to an array that calls the map method.

Varo = Object (this);

2. Assign Len to the length of the array O.

Varlen = o.length >>> 0;

4. If callback is not a function, throw the TypeError exception.

if ({}.tostring.call (callback)!= "[Object Function]") {

Thrownewtypeerror (callback + "is not a function");

}

5. If the parameter thisarg has a value, the T is assigned to THISARG, otherwise t is undefined.

if (Thisarg) {

T = Thisarg;

}

6. Create new array A, length is original array o length len

A =newarray (len);

7. Assign K to 0

k = 0;

8. Executes loops when K < Len.

while (K < Len) {

Varkvalue, Mappedvalue;

Traversal O,k is the original array index

if (KinO) {

Kvalue is the value corresponding to the index K.

Kvalue = o[K];

The execution callback,this points to T with three arguments. Kvalue: value, K: Index, O: original array.

Mappedvalue = Callback.call (T, Kvalue, K, O);

The return value is added to the new book Group A.

a[K] = Mappedvalue;

}

K Self-Increase 1

k++;

}

9. Returns the new array a

Returna;

};

}

a clever way to generate time stamps usually

The first way

Functiongettimestamp ()

{

Vartimestamp=newdate (). GetTime ();

vartimestampstring = timestamp.tostring ()//must convert string

Oldtimestamp = timestampstring;

returntimestampstring;

}

The second way

Newdate (). toString ()//can achieve the same effect, more concise

How to use the MD5 encryption method:

Reference GOOGLE,MD5 Encrypted library file: Http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js

Actually quite simple, inside CRYPTOJS.SHA1 (), direct reference encryption can, give a chestnut:

Just call straight on.

varkeyvaluestring = "DDDDD";

Sign = CRYPTOJS.SHA1 (keyvaluestring). toString ();

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.