Manipulation of JavaScript strings

Source: Internet
Author: User

  Usually when we write JS code, one of the most frequent operations may be related to the operation of the character, while in the interview also often design string conversion problem, today just will see the information and predecessors of the experience summed up, finishing as follows, I hope you can add and correct.

1. Non-string conversion to string 1.1 raw value to string
value Convert to String value Convert to String
Undefined "Undefined" 0 "0"
Null "NULL" NaN "NaN"
True "True" Infinity "Infinity"
False "False" -infinity "-infinity"
1.2 Object goto String

 What if it is {} , [] and the function{} object goes to the string?

The object is converted to a string, and there are two methods called: toString() and valueOf() . The calling rule is this:

    • This method is called if the object has a toString() method. If it returns a primitive value (undefined, null, number, Boolean, String), JavaScript converts the value to a string and returns the string result.
    • If the object has no toString() methods, or if the method does not return a primitive value, then JavaScript calls the valueOf() method. If this method is present, JavaScript calls it. If the return value is the original value, JavaScript converts the value to a string and returns the string result.
    • Otherwise, JavaScript will not be able toString() valueOf() to get a raw value from or to throw an exception.

In fact, most of the cases will call toString() the method, let's look at it.

  1. The default toString() method, that is Object.prototype.toString() , does not return a valid value, as in the following example

    1 ({x:1, y:2}). toString () // = "[Object Object]"

  2. Array objects are customized in the prototype toString() , that is Array.prototype.toString() , there are some differences when the array is called toString() .

    1 var a = []; 2 var b = [1, 2, 3]; 3 a.tostring (); // = "" 4 b.tostring (); // = " the"

    The toString() method that overwrites the object when the data is called toString() . toString()method returns a string that consists of the return value of each element in the array that is toString() join() concatenated (separated by commas) by the calling method.

  3. The
  4. function object customizes toString () in the prototype, i.e. Function.prototype.toString () .
     1 (function (x) {f (x);}). ToString (); //  

    function object overrides from Object inheritance Object.prototype.toString ()   method. The toString ()   method of the function returns a string that represents the source code of the function. Specifically, it includes the function keyword, the formal parameter list, the curly braces, and the contents of the body.

  5. The
  6. date (Function) object customizes toString () in the prototype, i.e. Date.prototype.toString () .

     1   var  date = new   date ();  2  date.tostring (); //  = "Mon Dec 21:58:10 gmt+0800 (China Standard Time)"   

    date object overrides the Object.prototype.toString ()   method inherited from object. The toString ()   method of date always returns a string in American English date format. The toString ()   method is called automatically when a Date object is used as a literal value or for string connections.

  7. Regular (REGEXP) objects are customized in the prototype toString() , i.e. RegExp.prototype.toString() .

    1 var New REGEXP ("A+b+c"); 2 // = "/a+b+c/"

    The RegExp object overrides the method that object inherits from Object.prototype.toString() . For RegExp objects, the ToString method returns a string form of the regular expression.

2. Common Operations for strings

 The method defined in the string prototype object, about twenty or thirty, fully remember that so many methods for ordinary people is too difficult, but the common seven or eight methods should be remembered, the other only need to have an impression, use the time in the MDN to check it.

2.1 String Properties

  The string defaults to only two properties defined: length and prototype . lengthrepresents the length of a string; prototype

1 var mystr = "This is a string"; 2 //  +
2.2 String Lookup

  A string lookup corresponds to two methods: indexOf() , lastIndexOf() .

  • indexOf ()

    Str.indexof (searchvalue[, FromIndex])

    searchvalue: Represents the value that is being looked up; FromIndex: Represents the position in the string in which the method was called, can be any integer, and the default value is 0. The indexOf ()   method returns the location of the first occurrence of the specified value in a string object. Returns 1 if it does not exist.

     1   var  mystr = "This is a string"  2  Console.log (Mystr.indexof ("a")); //  = 8   
  • lastIndexOf()

    Str.lastindexof (searchvalue[, FromIndex])

    Searchvalue: Represents the value that is being looked up; FromIndex: Represents the position in the string in which the method was called, looking forward, can be any integer, and the default value is 0. lastIndexOf()method returns the last occurrence of the specified value in the string where the method was called, or 1 if not found. Look forward from behind the string, starting at FromIndex.

  • Summary : index() is the previous lookup, lastIndexOf() is from the back to look forward, two methods are only a different way to find, but the two methods are found in the index value has been unchanged.
2.3 Interception and segmentation of strings

 Here are four methods: slice() ,, split() , substring() substr() . The reason we put these four methods together is because we sometimes confuse them and look at their respective usages.

  • slice()The: slice() method extracts a part of the string and returns the new string.

    Str.slice (beginslice[, Endslice])

    Beginslice: Extracts the characters from the original string starting at the index (base 0) and, if the argument is negative, it represents starting from the penultimate character in the original string. Endslice: Ends the fetch string at the index (base 0), and if omitted, slice is extracted to the end of the string, and if the argument is negative, it represents the end of the last character in the original string:

    1 var mystr = "This is a string"; 2 //  3//= "is"

  • split () : split ()   method by splitting a string into substrings to string The object is split into a string array.

    Str.split ([separator][, limit])

    separator: Specifies the character (string) used to split the string. Limit: An integer that defines the number of split fragments returned.

     1   var  mystr = "This is a string"  2  Console.log (Mystr.split ("")); // => ["This", "is", "a", "string"]  3  Console.log (Mystr.split ("", 3)); // => ["This", "is", "a"]   
  • substring () : substring ()   Returns a substring between two indexes (or to the end of a string) of a string.

    str.substring (indexa[, Indexb])

    indexa: An integer between 0 and the length of the string. INDEXB: (optional) An integer between 0 and the length of the string.

     1   var  mystr = "This is a string"  2  Console.log (mystr.substring (2)); // => "is a string"  3  Console.log (mystr.substring (2, 3)); // => "I"   
  • substr () : substr ()   method returns the specified number of characters from the specified position in the string.

    Str.substr (start[, length])

    start: the position at which to begin extracting characters. Length: The number of characters extracted.

     1   var  mystr = "This is a string"  2  Console.log (MYSTR.SUBSTR (2)); // => "is a string"  3  Console.log (Mystr.substr (2, 2)); // => "is"   
  • Summary : Four methods of each use as above, there are one or two places to note: split() The return is an array, you can remember this, split behind a T, you can look at [ , that is, the array; The method that involves the interception of index is not the tail.
2.4 String Index

  The index of a string involves two methods: indexOf() , charOf() .

  • IndexOf () : Returns the location of the first occurrence of the specified value in a string object. The lookup starts from the FromIndex position and returns 1 if it does not exist.

    Str.indexof (searchvalue[, FromIndex])

    searchvalue: A string representing the value being looked up. FromIndex: Represents the position in the string in which the method was called to begin the lookup. can be any integer. The default value is 0. If FromIndex < 0 finds the entire string (as if it were passed in 0).

     1   var  mystr = "This is a string"  2  Console.log (Mystr.indexof ("a")); //  = 8   
  • charOf(): Returns the character at the specified position in the string.

    Str.charat (Index)

    index:0 to an integer of string length-1.

    1 var mystr = "This is a string"; 2 // = "a"
2.5 String Merging

  Involves a method: concat() .

    • concat(): Merges one or more strings with the original string, forming a new string and returning.

      String.Concat (string2, string3[, ..., STRINGN])

      STRING2...STRINGN: Multiple strings connected to the original string

      1 var myStr1 = "This is"; 2 var myStr2 = "a string"; 3 // = "This is a string"
2.6 String Matching

  Two methods are involved: match() ,search()

  • match(): When a string is matched to a regular expression (regular expressions), the match() method extracts the match and returns an array. If the regular expression does not have a G flag, returns the same result as regexp.exec (str). And the returned array has an extra input property that contains the original string. In addition, you have an index property that represents the index of the match result in the original string (starting at 0). If the regular expression contains a G flag, the method returns an array containing all the matching results. If no match is reached, NULL is returned.

    Str.match (RegExp);

    RegExp: A regular Expression object. If a non-regular expression object is passed in, it is implicitly converted to a regular expression object using new RegExp (obj).

    1 var mystr = "This is a string"; 2 var pattern1 =/i[a-z]/; 3 var pattern2 =/i[a-z]/g; 4 Console.log (Mystr.match (PATTERN1)); // =>["is", index:2, Input: "The is a string"] 5 Console.log (Mystr.match (pattern2)); // =>[' is ', ' is ', ' in ']
  • search(): Performs a lookup to see if the string object matches a regular expression. If the match succeeds, search () returns the index of the first occurrence of the regular expression in the string. Otherwise, return-1.

    Str.search (RegExp)

    RegExp: A regular Expression object. If a non-regular expression object is passed in, it is implicitly converted to a regular expression object using new RegExp (obj).

    1 var mystr = "This is a string"; 2 var pattern =/i[a-z]/; 3 Console.log (Mystr.search (pattern)); // = 2 4 Console.log (Mystr.search ("z")); // + =-1
2.7 String Case Conversion

toLowerCase () , touppercase () .

    • toLowerCase(): The string value of the calling method is converted to lowercase and returned.

      1 var mystr = "This is a String"; 2 // = "This is a string"
    • toUpperCase(): Converts the string value of the method that is called to uppercase and returns.

      1 var mystr = "This is a String"; 2 // = "This is A STRING"
3 Summary

The above is my approximate summary of the operation of the string, there may be a need to improve and correct the place, I hope that there are ideas and suggestions, I hope we have a lot of messages.

Manipulation of JavaScript strings

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.