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 "":
VaR confirmstring = "You did not enter a response to the last" +
"Question. Submit Form anyway? ";
VaR confirmvalue = confirm (confirmstring );
However, this method can only be used when the text is rendered as HTML content, such as a warning or confirmation dialog box. In this case, replace it with "<br>:
VaR htmlstring = "first line of string. <br> 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 them:
var name = document.form1.txt username. value. tolowercase ();
If (name = "urname")
{< br> // statements go here.
}< br> 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.
Pay special attention to the type and consistency of the two strings when determining whether they are equal.
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.
SometimesCodeThe logic of 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 used to strongly typedProgramming Language(Such as C #, Java, etc.), you can continue your habit (type conversion) Here, it will also enhanceProgramReadability.
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 initialization has been obtained.
Strings. Sort (function (a, B) {return a. localecompare (B)}); // call the sort () method for sorting
VII. SEARCH strings
Problem:
Determines whether a string contains another string.
Solution:
Use the indexof () method of string:
Strobj. indexof (substring [, startindex])
Strobj is the string to be judged, and substring is the substring to be searched in strobj. startindex is optional, indicating the start position of the search (based on the 0 Index). If startindex is omitted, search from strobj. If startindex is smaller than 0, it starts from 0. If startindex is greater than the maximum index, it starts from the maximum 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 the following:
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. 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, and substring is the substring to be searched in strobj. startindex is optional, indicating the start position of the search (based on the 0 Index). If startindex is omitted, search from the end of strobj. If startindex is smaller than 0, it starts from 0. If startindex is greater than the maximum index, it starts from the maximum 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
Problem:
Obtains the Unicode encoding value of a character, and vice versa.
Solution:
To obtain the Unicode encoding of characters, you can use the string. charcodeat (INDEX) method, which is defined:
Strobj. charcodeat (INDEX)
Index is the position of the specified character in the strobj object (based on the 0 Index). 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 does not contain any character, the return value is Nan.
To convert unicode encoding to a character, use the 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"
/**
1. Trim string
*/
Function ltrim (STR)
{
VaR whitespace = new string ("");
VaR S = new string (STR );
If (whitespace. indexof (S. charat (0 ))! =-1)
{
VaR J = 0, I = S. length;
While (j <I & whitespace. indexof (S. charat (j ))! =-1)
{
J ++;
}
S = S. substring (J, I );
}
Return S;
}
Function rtrim (STR)
{
VaR whitespace = new string ("");
VaR S = new string (STR );
If (whitespace. indexof (S. charat (S. Length-1 ))! =-1)
{
VaR I = S. Length-1;
While (I> = 0 & whitespace. indexof (S. charat (I ))! =-1)
{
I --;
}
S = S. substring (0, I + 1 );
}
Return S;
}
Function trim (STR)
{
Return rtrim (ltrim (STR ));
}
/* 2. Email validator */
Function checkmail (email ){
Email = trim (email );
VaR rep =/^ W + ([-+.] W +) * @ w + ([-.] W + )*. W + ([-.] W +) * $ /;
// Alert (REP. Test (email ));
If (email = "" | email. Length <5 | email. length> 50 ){
Return false;
} Else if (REP. Test (email )){
Return true;
} Else {
Return false;
}
}