Common several JS difficult points, Match,charat,charcodeat,map,search

Source: Internet
Author: User
Tags square root

JavaScript Match () method

Definition 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 instead of the position of the string.

    1. Grammar
    2. Matches a string, returning the specified value
    3. Stringobject.match (Searchvalue)
    4. Matches the regular, returning the specified value
    5. Stringobject.match (RegExp)


Use Match () to retrieve a string example:
    1. <body>
    2. <script type= "Text/javascript" >
    3. var str= "Hello world!"
    4. document.write (Str.match ("World") + "<br/>")
    5. document.write (Str.match ("World") + "<br/>")
    6. document.write (Str.match ("worlld") + "<br/>")
    7. document.write (Str.match ("world!"))
    8. </script>
    9. </body>


The final result is, world,null,null,world!


Use Match () to retrieve a matching example of a regular expression:
    1. <body>
    2. <script type= "Text/javascript" >
    3. var str= "1 plus 2 equal 3";
    4. The regular expression here must be preceded by a G, global match, or it will match a value that returns
    5. document.write (Str.match (/\d+/g))
    6. </script>
    7. </body>

In general, we use match for more than regular, and we can use it to proxy indexof and LastIndexOf to determine if this value exists in the string.


JavaScript Search () method

Definition and usage

The search () method retrieves the substring specified in the string, or retrieves a substring that matches the regular expression, retrieves the starting position of the matched substring, fails to retrieve the value, and returns-1.

    1. Grammar
    2. Stringobject.search (RegExp)
    3. 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.
    4. To perform a search that ignores the case, append the flag I.
Copy Code

Search () Example:

    1. <script type= "Text/javascript" >
    2. var str= "Visit w3school!"
    3. document.write (Str.search (/w3school/))
    4. </script>


The return index value of 6,search is usually used with regular mates to achieve the indexof effect.


JavaScript charAt () method

Definition and usage

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

Note that JavaScript does not have a character data type that differs from the string type, so the returned character is a string of length 1.
    1. Grammar
    2. Returns a string at the specified position
    3. Stringobject.charat (Index)


Chartat instances:
    1. <script type= "Text/javascript" >
    2. var str= "Hello world!"
    3. document.write (Str.charat (1))
    4. </script>


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


JavaScript charCodeAt () method

Definition 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.

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 character string.

    1. Grammar
    2. Stringobject.charcodeat (Index)


charCodeAt () instance

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

    1. <script type= "Text/javascript" >
    2. var str= "Hello world!"
    3. document.write (Str.charcodeat (1))
    4. Returns the Unicode encoding of H 101
    5. </script>



JS in Array.prototype.map () method

Definition and usage

The map () method returns a new array that consists of a return value from each element in the original array that invokes a specified method.

    1. Grammar
    2. Array.map (callback[, Thisarg])
    3. Callback elements in the original array return a new element after the method.
    4. The first argument of Currentvalue,callback, the element that is currently passed in the array.
    5. The second argument of Index,callback, the index of the element that is currently being passed in the array.
    6. The third argument of Array,callback, which calls an array of map methods.
    7. Thisarg executes the callback function when this object is pointed to.


The map method invokes the callback function sequentially for each element in the original array. Callback the return value after each execution is combined to form a new array. The callback function will only be called on the indexed index;Those who have never been assigned value or used

Delete-deleted indexes are not called。 The callback function is automatically passed in three parameters: an array element, an element index, and the original array itself.

The first example of using a map ():

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

    1. function Fuzzyplural (single) {
    2. var result = Single.replace (/o/g, ' e ');
    3. if (single = = ' Kangaroo ') {
    4. result + = ' se ';
    5. }
    6. return result;
    7. }
    8. var words = ["foot", "Goose", "Moose", "kangaroo"];
    9. Console.log (Words.map (fuzzyplural));
    10. Final results ["feet", "geese", "Meese", "Kangareese"]
An example of the square root of each element in an array

    1. var numbers = [1, 4, 9];
    2. var roots = Numbers.map (MATH.SQRT);
    3. /* The value of roots is [1, 2, 3], the value of numbers is still [1, 4, 9] */


Using the Map method on a string
    1. var map = Array.prototype.map
    2. var a = Map.call ("Hello World", function (x) {return x.charcodeat (0);})
    3. The values for a are [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]


    1. <! DOCTYPE html>
    2. <meta charset= "UTF-8" >
    3. <title></title>
    4. <body>
    5. <script type= "Text/javascript" >
    6. var map = Array.prototype.map
    7. var a = Array.prototype.map.call ("Hello World", function (x) {return x.charcodeat (0);})
    8. The values for a are [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
    9. alert (a);
    10. </script>
    11. </body>


Map compatible with legacy environments

Map is a newly added method in the recent ECMA-262 standard, so some older browsers might not have implemented the method. In browsers that do not natively support the map method, you can use the following Javascript code to implement it. is used by
The algorithm is ECMA-262, the 5th edition stipulates. Assume that the object, TypeError, and Array have their original values. And the original value of Callback.call is also Function.prototype.call.
  1. Implement ECMA-262, Edition 5, 15.4.4.19
  2. Reference: http://es5.github.com/#x15.4.4.19
  3. if (! Array.prototype.map) {
  4. Array.prototype.map = function (callback, THISARG) {
  5. var T, A, K;
  6. if (this = = null) {
  7. throw new TypeError ("This is a null or not defined");
  8. }
  9. 1. Assign o to the array that calls the map method.
  10. var O = Object (this);
  11. 2. Assign Len to the length of the array O.
  12. var len = o.length >>> 0;
  13. 4. If callback is not a function, the TypeError exception is thrown.
  14. if ({}.tostring.call (callback)! = "[Object Function]") {
  15. throw new TypeError (callback + "is not a function");
  16. }
  17. 5. If the parameter thisarg has a value, the T is assigned the value Thisarg; otherwise t is undefined.
  18. if (Thisarg) {
  19. T = Thisarg;
  20. }
  21. 6. Create new array A, length is the original array o length len
  22. A = new Array (len);
  23. 7. Assign a value of K to 0
  24. k = 0;
  25. 8. When K < Len executes the loop.
  26. while (K < Len) {
  27. var kvalue, Mappedvalue;
  28. Traverse O,k as the original array index
  29. if (k in O) {
  30. Kvalue the value corresponding to the index K.
  31. Kvalue = o[K];
  32. The execution callback,this points to T, with three parameters. Kvalue: value, K: Index, O: the original array.
  33. Mappedvalue = Callback.call (T, Kvalue, K, O);
  34. The return value is added to the new book Group A.
  35. a[K] = Mappedvalue;
  36. }
  37. K Self-Increment 1
  38. k++;
  39. }
  40. 9. Returns the new array a
  41. return A;
  42. };
  43. }

Common several JS difficult points, Match,charat,charcodeat,map,search

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.