The related operation of string in JS

Source: Internet
Author: User

(Transferred from: http://www.cnblogs.com/zhaoxinxin/articles/1402733.html)

One, the creation of a string there are several ways to create a string.

The simplest is to enclose a set of characters in quotation marks, which can be assigned to a string variable.

var mystr = "Hello, string!";

You can enclose a string in double or single quotation marks, but be aware that the pair of quotes that are defined as strings must be the same and cannot be mixed.

like var myString = "Fluffy is a pretty cat." Such a statement is illegal.

Allows the use of two types of quotation marks, making certain operations simple, such as embedding one type of another: document.write (' ’);

We created several strings in the script above, but in essence, they are not real string objects, they are exactly the values of the string type. To create a string object, you can use the following statement: var strobj = new String ("Hello, string!"); Using the typeof operator view, it is found that the MyStr type above is string and the Strobj type is object. If you want to know the length of the string, use its Length property: String.Length. Gets the character used by the specified position of the string: String.charat (index);

Two, string splicing problem: splicing two or more strings into a large string solution: very simple, with a "+" two Strings "added": var longstring = "One Piece" + "plus one more piece."; To accumulate multiple strings into a single string, you can also use the "+ =" Operator: var result = ""; Result + = "My name is Anders" result + = "and my age is 25"; To add line breaks in a string, you need to use the escape character "\ n": var confirmstring = "You didn't do not enter a response to the last" + "question.\n\nsubmit form Anyw Ay? "; var confirmvalue = confirm (confirmstring); However, this method can only be used in cases such as warning, confirmation dialog box, if the text is rendered as HTML content, it is invalid, at this time with "
"Replace it: var htmlstring =" First line of string.
Second line of String. "; document.write (htmlstring); The string object also provides the method Concat (), which accomplishes the same function as "+": String.Concat (value1, value2, ...) but the concat () method is obviously less intuitive than "+".

Third, access string substring problem: Get a copy of a string part. Solution: Use the substring () or slice () method (nn4+, ie4+), which describes their specific usage.

The prototype for 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), and the second argument to is optional, which specifies the substring at the end of the original string ( Based on the 0 index), in general, it should be larger than the from, if it is omitted, then the substring will continue to the end of the original string.

What if the parameter from is accidentally larger than the parameter? JavaScript automatically mediates the starting and ending positions of substrings, that is, substring () always starts with the smaller of the two parameters and ends with the larger one. Note, however, that it contains the character at the beginning of the position, but does not contain that character at the end position. var fullstring = "Every dog has he day."; var section = fullstring.substring (0, 4); Section is ' ever '. Section = fullstring.substring (4, 0); Sections is also "ever". Section = fullstring.substring (1, 1); Section was an empty string.section = fullstring.substring (-2, 4); Section is "ever", same as Fullstring.substring (0, 4); The prototype of Slice () is: The String.slice (start, end) parameter start indicates the starting position of the substring, and if it is negative, it can be understood as the beginning of the countdown, for example-3 for the beginning of the third from the bottom; The parameter end indicates the end position, as with start, It can also be a negative number, and its meaning is also expressed to the end of the countdown. Slice () parameter can be negative, so more flexible than substring (), but less tolerant, if start is larger than end, it will return an empty string (example slightly). Another method is substr (), the prototype is: String.substr (start, length) from the prototype can see the meaning of its parameters, start represents the starting position, length is the length of the substring. The JavaScript standard does not advocate the use of this method.

Four, the case of the string conversion problem: a text box on your page to receive the user's input information, such as the city, and then you will be based on his city's different processing, then naturally use the string comparison, then before the comparison, it is best to make the case conversion, so long as the conversion of the situation can be considered , or you want to collect data on a page, and then store that data in a database, and the database just receives uppercase characters; In these cases, we will consider case-by-case conversion of the string.

Solution: Use toLowerCase () and toUpperCase () method: var city = "Shanghai"; City = City.tolowercase (); City was "Shanghai" now.

V. Determine whether two strings are equal: For example, you want to compare a user's input value to a known string.

Solution: First convert the user's input values all to uppercase (or lowercase), and then compare: var name = Document.form1.txtUserName.value.toLowerCase (); if (name = = "Urname") {// Statements go here.} JavaScript has two equality operators. One is completely backwards compatible, the standard "= =", if the two operand types are inconsistent, it will at some point automatically type conversion of the operand, consider the following assignment statement: var stra = "I love you!"; var StrB = new String ("I love you!"); These two variables contain the same sequence of characters, but the data types are different, the former is string, the latter is object, and when you use the "= =" operator, JavaScript tries various evaluation to detect whether the two are equal in some case. So the following expression results in True:stra = = StrB. The second operator is "strict", "= = =", which is not so tolerant when evaluating, and does not perform type conversions. So the expression stra = = = Strb The value is false, although both variables hold the same value. Sometimes the logic of the code requires you to determine whether the two values are unequal, there are also two options: "! =" and the Strict "!==", their relationship is similar to "= =" and "= = =". Discussion: "= =" and "! =" look for the matching of values whenever possible, but you might want to make explicit type conversions 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 let "= =" help you complete the type conversion: if (Document.form1.txtAge.value = = Somenumericvar) {...} can also be converted in advance: if ( parseint (document.form1.txtAge.value) = = Somenumericvar) {...} If you are more accustomed to a strongly typed programming language (such as C#,java, etc.), then you can continue your habit (type conversion) here, This will also enhance the readability of the program. One situation to note is the locale of the computer. If you compare strings with "<" and ">", then JavaScript compares them as Unicode, but obviously people don't read text as Unicode when they browse the Web:) In Spanish, for example, according to the traditional sort, "ch" will be ranked as a character between "C" and "D".Localecompare () provides a way to help you use the character collation under the default locale. var strings; An array of strings to sort, assuming that the Strings.sort has been initialized (function (b) {return a.localecompare (b)}); To sort by calling the sort () method

Six, String lookup problem: Determine whether a string contains another string. Solution: Use the IndexOf () method of string: Strobj.indexof (substring[, StartIndex]) Strobj for the string to be judged, subString for the substring to find in Strobj, startindex is optional, indicating the start of the lookup (based on the 0 index), if startindex is omitted, it is found from the beginning of strobj, if startindex is less than 0, then 0 if startindex is greater than the maximum index, Starts at the maximum index. IndexOf () returns the start position of substring in strobj, or 1 if not found. In the script, you can use this: if (Largestring.indexof (shortstring)! =-1) {//If included, handle accordingly;} Maybe a string will contain another string more than once, At this point the second parameter startindex may come in handy, the following function shows how to obtain a string containing the number of times of 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 find in Strobj, startindex is optional, indicating the starting position of the lookup (based on the 0 index), and if startindex omitted, it is found from the end of Strobj, if startindex is less than 0, then starting from 0. If startindex is greater than the maximum index, start at the maximum index. This method looks from right to left, returns the last position of substring in strobj, and returns 1 if not found.

Vii. conversion between Unicode values and characters in a string: Gets the Unicode encoded value of one character, and vice versa. Solution: To get Unicode encoding for a character, you can use the String.charcodeat (index) method, which 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-bit integer between 0 and 65535. For example: var strobj = "ABCDEFG"; var code = strobj.charcodeat (2); Unicode value of character ' C ' is 67 the return value is Nan if there are no characters at index specified. To convert a Unicode encoding to a character, using the String.fromCharCode () method, note that it is a "static method" of a string object, meaning that you do not need to create a string instance before use: String.fromCharCode (C1, C2, ...) It accepts 0 or more integers, returns a string that contains the characters specified by each parameter, for example: var str = String.fromCharCode (72, 101, 108, 108, 111); str = = "Hello" discussion: Unicode contains the character set of many written languages in the world, but do not expect this character to display correctly when a warning dialog box, text box, or page is rendered because Unicode contains a single character. If the character set is not available, the page will be displayed as a question mark or other symbol. A typical North American computer will not be able to display Chinese characters on the screen, unless the English 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.