JavaScript: String operations in JavaScript, Javascript tutorial
I. Overview
Strings are almost everywhere in javascript. When you process user input data and read or set DOM object attributes, there are more strings when operating cookies .... 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.
Ii. Create a string
There are several methods to create a string. The simplest is to enclose a group of characters in quotation marks and assign them to a string variable.
Var myStr = "Hello, String! ";
You can use double quotation marks or single quotation marks to enclose strings. However, you must 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 above script, but they are essentially not real string objects. They are string-type values accurately. To create a String object, use the following statement: var strObj = new String ("Hello, String! ");
If you use the typeof operator, you will find 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:
Concatenates two or more strings into a large string.
Solution:
It is very simple. Just use "+" 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 the case of warnings, confirmation dialog boxes, and so on. If this text is rendered as HTML content, it will be invalid"
"Replace it:
Var htmlString = "First line of string.
Second line of string .";
Document. write (htmlString );
The String object also provides the concat () method, which performs the same functions as "+:
String. concat (value1, value2 ,...)
However, the concat () method is obviously not as intuitive and concise as "+.
4. Access string substrings
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,)
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)
The start parameter indicates the starting position of the substring. If it is a negative number, it can be understood as the last few, for example,-3 indicates starting from the last three; the end parameter indicates the end position, like start, it can also be a negative number, which means that the last few ends. 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)
From the prototype, we can see the meaning of its parameters. start indicates the starting position, and length indicates the length of the substring. This method is not recommended for JavaScript standards.
V. case-insensitive conversion of strings
Problem:
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, then you will naturally use string comparison, before comparison, it is best to perform case-sensitivity conversion so that you only need to consider the case after conversion; or you need to collect data on the page and then store the data in the database, the database only receives uppercase characters. In these cases, we must consider case-insensitive conversion of strings.
Solution:
Use the toLowerCase () and toUpperCase () methods:
Var city = "ShanGHai ";
City = city. toLowerCase (); // city is "shanghai" now.
6. Determine whether two strings are equal
Problem:
For example, you want to compare user input values with 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 to evaluate various types of values, to check whether the two are equal under certain 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 ){...}
Conversion can also be performed in advance:
If(parseInt(document.form1.txt Age. 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.
[1] [2] Next page