Careful collection of JavaScript strings

Source: Internet
Author: User

When I first started writing JavaScript and encountered some problems to solve, I found that I often needed Google search or Mozilla reference, to find the exact syntax and parameter definitions and string operation methods. It seems that experts have come over like this. After several years of programming, I have accumulated a lot of useful information, so today's article will share some examples and brief descriptions of the most common and useful string-related methods summarized over the past few years. It is easy for programmers to use for quick reference. Of course, the most experienced developers are familiar with these operations, but I think this is a good way to help beginners understand these functions and help you use simple syntax. After complex operations, you can convert a string to a number, Boolean value, or string object: 1 var myNumber = 24; // 242 var myString = myNumber. toString (); // "24" var myNumber = 24; // 24var myString = String (myNumber ); // "24" Splits a string into multiple sub-strings. to distinguish a string from a sub-string array, you can use the split () method: 1 var myString = "coming, apart, at, the, commas "; 2 var substringArray = myString. split (","); // ["coming", "apart", "at", "the", "commas"] 3 var arrayLimited = myString. split (",", 3); // ["coming", "apart", "at"] The second parameter in the last row limits the number of items specified by the array parameter. Obtain the length of a string. The length attribute of the string is 1 var myString = "You're quite a character. "; 2 var stringLength = myString. length; // 25 There are two methods to find a substring in a string. Use indexOf (): 1 var stringOne = "Johnny Waldo Harrison Waldo"; 2 var wheresWaldo = stringOne. indexOf ("Waldo"); // 7 indexOf () method searches for the first parameter of the substring starting from the beginning of the string (passed), and returns the starting position of the first occurrence of the substring. Use lastIndexOf (): 1 var stringOne = "Johnny Waldo Harrison Waldo"; 2 var wheresWaldo = stringOne. lastIndexOf ("Waldo"); // 22 The lastIndexOf () method is identical, except that it returns the starting position of the last occurrence of the passed substring. In the two methods, if the Sub-string is not found, the return value is-1, and an optional second parameter is allowed to indicate that the position of the character you want to start searching in the string replaces part or all of the string to be replaced by a substring, you can use replace (): 1 var slugger = "Josh Hamilton"; 2 var betterSlugger = slugger. replace ("h Hamilton", "e Bautista"); 3 console. log (betterSlugger); // "Jose Bautista" the first parameter is the substring you want to replace, and the second parameter is the new substring. This will only Replace the first instance of the matched substring. Replace all instances of the matched substring with the global flag of the regular expression: 1 var myString = "She sells automotive shells on the automotive shore"; 2 var newString = myString. replace (/automotive/g, "sea"); 3 console. log (newString); // "She sells sea shells on the sea shore" the second parameter can include a special replacement mode or a function. Find the character to be searched for at the specified position. You can use the charAt () method: var myString = "Birds of a Feather "; var whatsAtSeven = myString. charAt (7); // "f" is usually in JavaScript, the first position in the referenced string is "0", rather than "1 ". Alternatively, you can use charCodeAt () to give it to you, instead of the character code of the character itself: 1 var myString = "Birds of a Feather"; 2 var whatsAtSeven = myString. charCodeAt (7); // "102" 3 var whatsAtEleven = myString. charCodeAt (11); // "70" note that the character code of the uppercase letter "F" (11) and the character code of the lowercase letter "f" (7) different from the escape code. When you connect multiple strings, you use the addition operator (+) in most cases ). However, you can also use the CONCAT () method: 1 var stringOne = "Knibb High football"; 2 var stringTwo = stringOne. concat ("rules. "); //" Knibb High football rules "you can append multiple strings one by one (in the order they appear ): 1 var stringOne = "Knibb"; 2 var stringTwo = "High"; 3 var stringThree = "football"; 4 var stringFour = "rules. "; 5 var finalString = stringOne. concat (stringTwo, stringThree, stringFour); 6 console. log (finalString); // "Knibb high Football rules. "There are three different methods to create a new string value by extracting a string (forming a new string): Use slice () method: 1 var stringOne =" abcdefghijklmnopqrstuvwxyz "; 2 var stringTwo = stringOne. slice (5, 10); // "fghij" Use the substring () method: var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne. substring (5, 10); // The first parameter of the two slice () and substring () methods is the substring you want to start, the character ending string in the string after the second parameter (optional. Therefore, in the preceding example, the parameter "5, 10" refers to a character ranging from 5 to 9 to create a new string. Use SUBSTR () var stringOne = "abcdefghijklmnopqrstuvwxyz"; var stringTwo = stringOne. substr (5, 10); // "fghijklmno" SUBSTR (). The first parameter indicates the start character of the new string, and the second parameter is optional. However, the total number of characters indicated by the second parameter should include the starting character "5. There are four methods to convert a string to uppercase or lowercase for case conversion. There are two strings converted to all uppercase: 1 var stringOne = "Speak up, I can't hear you. "; 2 var stringTwo = stringOne. toLocaleUpperCase (); // "speak up, I CAN't HEAR YOU" 3 var stringThree = stringOne. toUpperCase (); // "speak up, I CAN't HEAR YOU" converts a string TO lowercase: 1 var stringOne = "YOU DON't HAVE TO YELL "; 2 var stringTwo = stringOne. toLocaleLowerCase (); // "you don't have to yell" 3 var stringThree = stringOne. toLowerCase (); // "you The don't have to yell pattern matches in a string matching pattern. You can use two methods, which basically work in the same way. The match () method of a string is called, and the regular expression is: 1 var myString = "How much wood cocould a wood chuck"; 2 var myPattern = /. ood/; 3 var myResult = myString. match (myPattern); // ["wood"] 4 var patternLocation = myResult. index; // 95 var originalString = myResult. input // "How much wood cocould a wood chuck" exec () method is called as a regular expression object, and the string is used: var myString = "How much wood cocould a wood chuck"; var myPattern = /. huck /; Var myResult = myPattern.exe c (myString); // ["chuck"] var patternLocation = myResult. index; // 27var originalString = myResult. input // "How much wood cocould a wood chuck" for the two methods, only the first match is returned. If no match is found, a null value is returned. You can also use the search () method, which accepts a regular expression as a unique parameter and returns the location where the mode first appears: 1 var myString = "Assume"; 2 var patternLocation = myString. search (/ume/); // 3 if no match is found, the method returns "-1 ". To compare the sorting order of two strings, you can compare the two strings to see which letter uses localeCompare first. There are three possible return values: 1 var myString = "chicken "; 2 var myStringTwo = "egg"; 3 var whichCameFirst = myString. localeCompare (myStringTwo); //-1 (Response t Chrome, which returns-2) 4 whichCameFirst = myString. localeCompare ("chicken"); // 05 whichCameFirst = myString. localeCompare ("apple"); // 1 (Chrome returns 2) stringObject. localeCompare (target) // shows the formula. If stringOb If the value of ject is smaller than target, localeCompare () returns a value smaller than 0. If the value of stringObject is greater than target, this method returns a value greater than 0. If the two strings are equal or there is no difference according to the local sorting rules, this method returns 0. Because the browser can return any negative or positive numbers before and after the result, it is best to use if (result <0) instead of if (result =-1 ), the latter cannot be run in Chrome.

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.