String operations in JavaScript

Source: Internet
Author: User
Tags string indexof
String operations in JavaScript 1. Summary strings are almost everywhere in JavaScript. When you process user input data, when you read or set the attributes of a DOM object, when you operate cookies, of course there are more .... The core part of JavaScript provides a set of attributes and... syntaxHighlighter. string operations in JavaScript a. Summary strings are almost everywhere in JavaScript. When you process user input data, when you read or set the attributes of a DOM object and perform cookie operations, of course there are more .... The core part of JavaScript provides a set of attributes and methods for common string operations, such as splitting strings, changing the case sensitivity of strings, and operating on substrings. Most browsers can also benefit from powerful regular expressions, because it greatly simplifies a large number of string operation tasks, but it also requires you to overcome a steep learning curve. Here, we mainly introduce some operations on the string itself, and regular expressions will be involved in subsequent essays. 2. Create a string using several methods. The simplest is to enclose a group of characters in quotation marks and assign them to a string variable. Var myStr = "Hello, String! "; Double quotation marks or single quotation marks can be used to enclose strings. However, note that a pair of quotation marks defining strings must be the same and cannot be mixed. Declarations such as var myString = "Fluffy is a pretty cat. '; are invalid. Two quotation marks are allowed to simplify some operations, such as embedding one type into another: document. write (""); we have created several strings in the script above, but they are essentially not really string objects. To be precise, they are string-type values. To create a String object, use the following statement: var strObj = new String ("Hello, String! "); Using the typeof operator, you can see that the above myStr type is string, and the strObj type is object. If you want to know the length of a string, use its length attribute: string. length. How to Use the character at the specified position of the string: string. charAt (index); 3. String concatenation problem: concatenate two or more strings into a large string solution: very simple, use a "+" to add two strings ": var longString =" One piece "+" plus one more piece. "; to accumulate multiple strings into one, you can also use the" + = "OPERATOR: var result = ""; result + = "My name is Anders" result + = "and my age is 25"; to add a line break to a string, use the Escape Character "\ n ": var confirmString = "You did not enter a response to the last" + "question. \ n \ nSubmit form anyway? "; Var confirmValue = confirm (confirmString); however, this method can only be used in situations such as warning and confirmation dialog boxes. if this text is rendered as HTML content, it will be invalid, use"
"Replace it: var htmlString =" First line of string.
Second line of string. "; document. write (htmlString); The String object also provides the concat () method, which completes the same function as "+": string. concat (value1, value2 ,...) however, the concat () method is obviously not as intuitive and concise as "+. 4. substring access problem: obtain a copy of a part of a string. Solution: Use the substring () or slice () method (NN4 +, IE4 +). The following describes their usage. The prototype of substring () is string. substring (from, to) the first parameter from specifies the starting position of the substring in the original string (based on the 0 index); the second parameter to is optional, it specifies the substring at the end of the original string (based on the 0 Index). In general, it should be larger than from. If it is omitted, then the substring ends at the end of the original string. What if the from parameter is bigger than the parameter? JavaScript will automatically mediate the starting and ending positions of the substring, that is, the substring () always starts from the smaller of the two parameters and ends with the larger one. Note that it contains the character at the starting position, but does not contain the character at the ending position. Var fullString = "Every dog has his day. "; var section = fullString. substring (0, 4); // section is "Ever ". section = fullString. substring (4, 0); // section is also "Ever ". section = fullString. substring (1, 1); // section is an empty string. section = fullString. substring (-2, 4); // section is "Ever", same as fullString. substring (0, 4); the prototype of slice () is: string. slice (start, end) parameter start indicates the starting position of the substring. If it is a negative number, you can Returns the start Number of the last vertex. For example,-3 indicates starting from the last vertex. The end parameter indicates the end position. Like start, it can also be a negative number, the meaning also indicates the end of the last few. Slice () parameters can be negative, so it is more flexible than substring (), but not so tolerant. If start is larger than end, it returns an empty string (for example, omitted ). Another method is substr (). Its prototype is string. substr (start, length) shows the meaning of its parameters from the prototype. start indicates the starting position, and length indicates the length of the substring. This method is not recommended for JavaScript standards. 5. case-insensitive conversion of strings: there is a text box on your page to receive user input information, such as the city, and then you will perform different processing based on the different cities, in this case, you will naturally use string comparison. Before comparison, it is best to perform case-sensitive conversion so that you only need to consider the case after conversion. or you need to collect data on the page, the data is then stored in the database, and the database only receives uppercase characters. In these cases, we need to consider case-insensitive conversion of strings. Solution: Use toLowerCase () and toUpperCase () Methods: var city = "ShanGHai"; city = city. toLowerCase (); // city is "shanghai" now. 6. Determine whether the two strings are equal. For example, you want to compare the user input value with the known strings. solution: first, convert all user input values to uppercase (or lowercase), and then compare: var name = document.form1.txt UserName. value. toLowerCase (); if (name = "urname") {// statements go here .} javaScript has two equal operators. One is completely backward compatible, the standard "=". If the two operand types are inconsistent, it will automatically convert the type of the operand in some cases. Consider the following assignment statement: var strA = "I love you! "; Var strB = new String (" I love you! "); These two variables contain the same character sequence, but their data types are different. The former is string, and the latter is object. When the" = "operator is used, javaScript will try various evaluate to check if the two are equal under some circumstances. Therefore, the following expression returns true: strA = strB. The second operator is "strict" "=". It is not so tolerant in value evaluation and does not perform type conversion. Therefore, the value of the expression strA === strB is false, although the two variables hold the same value. Sometimes the logic of the Code requires you to determine whether two values are not equal. Here there are two options :"! = "And strict "! = ", Their relationships are similar to" = "and" = ". Discussion: "=" and "! = "When you evaluate the value, you will try to find the matching of the value, but you may still want to perform explicit type conversion before comparison to" help "them complete their work. For example, if you want to determine whether a user's input value (string) is equal to a number, you can enable "=" to help you complete type conversion: if(document.form1.txt Age. value = someNumericVar ){...} you can also convert if(parseInt(document.form1.txt Age in advance. value) = someNumericVar ){...} if you are more accustomed to strong programming languages (such as C # and Java), you can continue your habits (type conversion) Here, which will also enhance the readability of the program. Note that you need to set the computer region. If you use "<" and ">" to compare strings, JavaScript compares them as Unicode, but obviously, people do not read text as Unicode when browsing the Web page. For example, in Spanish, "ch" is traditionally sorted as a character between "c" and "d. LocaleCompare () provides a way to help you set character sorting rules in the default region. Var strings; // array of strings to be sorted. Assume that the strings has been initialized. sort (function (a, B) {return. localeCompare (B)}); // call the sort () method for sorting. 7. query the string: determines whether a string contains another string. Solution: Use the string indexOf () method: strObj. indexOf (subString [, startIndex]) strObj is the string to be judged, subString is the subString to be searched in strObj, and startIndex is optional, indicates the start position of the search (index based on 0). If startIndex is omitted, the search starts from strObj. If startIndex is smaller than 0, it starts from 0. If startIndex is greater than the maximum index, start from the largest index. IndexOf () returns the starting position of the subString in strObj. If no value is found,-1 is returned. In the script, you can use: if (largeString. indexOf (character string )! =-1) {// if it is included, perform corresponding processing;} a string may contain another string more than once, and the second parameter startIndex may be used in this case, the following function demonstrates how to obtain the number of times a string contains another string: function countInstances (mainStr, subStr) {var count = 0; var offset = 0; do {offset = mainStr. indexOf (subStr, offset); if (offset! =-1) {count ++; offset + = subStr. length ;}} while (offset! =-1) return count;} The String object has a method corresponding to indexOf (), lastIndexOf (): strObj. lastIndexOf (substring [, startindex]) strObj is the string to be judged, subString is the substring to be searched in strObj, and startIndex is optional, indicates the start position of the search (index based on 0). If startIndex is omitted, it will be searched from the end of strObj. If startIndex is smaller than 0, it will start from 0. If startIndex is greater than the maximum index, start from the largest index. This method is right-to-left lookup and returns the position of the subString in strObj. If it is not found,-1 is returned. 8. Conversion between Unicode values and characters in a string: Obtain the Unicode encoded value of a character, and vice versa. Solution: to obtain the Unicode encoding of characters, you can use string. the charCodeAt (index) method is defined as strObj. charCodeAt (index) index is the position of the specified character in the strObj object (based on the 0 index), and the return value is a 16-digit integer between 0 and 65535. For example: var strObj = "ABCDEFG"; var code = strObj. charCodeAt (2); // Unicode value of character 'C' is 67 if the index specified has no characters, the return value is NaN. To convert Unicode to a character, use String. fromCharCode () method, note that it is a "static method" of the String object, that is, you do not need to create a String instance before use: String. fromCharCode (c1, c2 ,...) it accepts 0 or multiple integers and returns a String that contains the characters specified by each parameter, for example, var str = String. fromCharCode (72,101,108,108,111); // str = "Hello": Unicode contains the character sets of many writing languages in the world, however, do not expect Unicode to be properly displayed in the warning dialog box, text box, or page because it contains one character. If the character set is unavailable, it is displayed as a question mark or another symbol on the page. A typical North American computer cannot display Chinese characters on the screen, unless the Chinese Character Set and Its font have been installed.

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.