String manipulation in JavaScript
I. Overview
Strings are almost ubiquitous in JavaScript, and when you are working with the user's input data, when you read or set the properties of a DOM object, while manipulating the cookie, there are of course more .... The core part of JavaScript provides a set of properties and methods for common string operations such as splitting strings, changing the case of strings, manipulating substrings, and so on.
Most current browsers can also benefit from powerful regular expressions, because it greatly simplifies a lot of string manipulation tasks, but it also requires you to overcome a somewhat steep learning curve. Here, the main is to introduce some operations of the string itself, the regular expression will be covered in a later essay.
Second, 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.
Two types of quotation marks are allowed, making certain operations easier, such as embedding one into 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);
Three, the concatenation of strings
Problem:
Stitching two or more strings into a single large string
Solution:
It is very simple to "add" two strings with a "+":
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 a line break to a string, you need to use the escape character "\ n":
var confirmstring = "You do not have enter a response to the last" +
"Question.\n\nsubmit form anyway?";
var confirmvalue = confirm (confirmstring);
But this method can only be used in situations such as a warning, confirmation dialog box, if the text is rendered as HTML content, it is not valid, and then "<br>" instead of it:
var htmlstring = "First line of String.<br>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, ...)
However, the concat () method is obviously less intuitive and concise than "+".
Iv. accessing substrings of a string
Problem:
Gets a copy of a part of a string.
Solution:
Using the substring () or slice () methods (nn4+, ie4+), the following describes their specific 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), and the second argument to is optional, which specifies that the substring is at the end of the original string (based on the 0 index), and generally it should be larger than the from, if it is omitted, The substring is then kept at 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); Section 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 for Slice () is: String.slice (start, end)
The argument start indicates the starting position of the substring, and if it is a negative number, it can be understood as the beginning of the countdown, for example-3 means starting from the last third; The parameter end represents the end position, as with start, it can also be negative, meaning it also indicates 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 (), whose prototype is: String.substr (start, length)
The meaning of its parameters can be seen from the prototype, start means the starting position, and length indicates the substring's lengths. The JavaScript standard does not advocate the use of this method.
V. Case conversion of strings
Problem:
On your page there is a text box to receive the user's input information, such as the city, 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 to collect data on the page, The data is then stored in the database, and the database just receives uppercase characters, and in these cases we consider the case conversion of the string.
Solution:
Use the toLowerCase () and toUpperCase () methods:
var city = "Shanghai";
City = City.tolowercase (); City was "Shanghai" now.
Six, determine whether two strings are equal
Problem:
For example, you want to compare a user's input value to a known string
Solution:
First, convert all of the user's input values to uppercase (or lowercase), and then compare the rows:
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 convert the operands, 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 "= = =".
Discuss:
"= =" and "! =" are looking 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 (a string) is equal to a number, you can let "= =" help you complete the type conversion:
if (Document.form1.txtAge.value = = Somenumericvar) {...}
You can also convert ahead of time:
if (parseint (document.form1.txtAge.value) = = Somenumericvar) {...}
If you are more accustomed to strongly typed programming languages (such as C#,java, etc.), then you can continue your habit (type conversion) here, which will also enhance the readability of your 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 it has been initialized
{}); To sort by calling the sort () method
Seven, the search for strings
Problem:
Determines whether a string contains another string.
Solution:
Use the IndexOf () method of the string:
Strobj.indexof (substring[, StartIndex])
Strobj is the string to be judged, substring is the substring to be searched for Strobj, startindex is optional, indicates the start of the lookup (based on the 0 index), and if startindex is omitted, it is located from the beginning of the strobj. If startindex is less than 0, start at 0 and start at the maximum index if startindex is greater than 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 it is included, deal with it accordingly;
}
Perhaps a string will contain another string more than once, when the second parameter startindex may come in handy, the following function shows how to find 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 for Strobj, startindex is optional, indicates the start of the lookup (based on the 0 index), and if startindex is omitted, it is found at the end of Strobj If startindex is less than 0, start at 0 and start at the maximum index if startindex is greater than the maximum index. This method looks from right to left, returns the last position of substring in strobj, and returns 1 if not found.
Viii. converting between Unicode values and characters in a string
Problem:
Gets the Unicode encoded value of a 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 the 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 takes 0 or more integers and returns a string that contains the characters specified by each argument, for example:
var str = String.fromCharCode (101, 108, 108, 111); str = = "Hello"
Discuss:
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 language character set and its font are installed.
String manipulation in JavaScript