JavaScript stri...LOGIN

JavaScript string

JavaScript String

Overview
Strings are almost everywhere in JavaScript. When you process user input data, when reading When getting or setting properties of DOM objects, when manipulating cookies, and of course much 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, operating substrings, etc.
Most current browsers can also benefit from the power of regular expressions, because it greatly simplifies a large number of string manipulation tasks, but it also requires you to overcome a somewhat steep learning curve. Here, we mainly introduce some operations on the string itself. Regular expressions will be covered in future essays.

Creation of string
There are several ways to create a string. The simplest is to enclose a set of characters in quotes, which can be assigned to a string variable.
var myStr = "Hello, String!";
You can use double quotes or single quotes to include the string, but be aware that the pair of quotes that delimit the string must be the same and cannot be mixed.
Declarations like var myString = "Fluffy is a pretty cat.'; are illegal.
Allows the use of two kinds of quotation marks, making certain operations simple, such as embedding one into another:

document.write("");

We created several strings in the above script, but in essence, they are not real string objects. To be precise, they are string type values ​​to create a string. Object, you can use the following statement: var strObj = new String("Hello, String!");

If you use the typeof operator, you will find that the type of myStr above is string, and strObj The type is object.

If you want to know the length of the string, use its length property: string.length
How to get the character at the specified position of the string: string.charAt (index);

String splicing

Problem:
Splicing two or more strings into one large string
Solution:
Very simple, just Use a "+" to "add" two strings:

var longString = "One piece " + "plus one more piece.";

To accumulate multiple strings into one string, you can also use the "+=" operator:


var result = "";
result += "My name is Anders"
result += " and my age is 25";

To add a newline character to a string, you need to 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);

But this method can only be used in situations like warnings and confirmation dialog boxes. If this text is presented as HTML content, it will be invalid. In this case, use "
" to replace it:

 var htmlString = "First line of string.
Second line of string.";
document.write(htmlString);

The String object also provides the method concat(), which performs the same function as "+":
string.concat(value1, value2, ...)
However, concat( ) method is obviously not as intuitive and concise as "+".

Accessing a substring of a string
Question:
Get a copy of a part of a string.
Solution:
Use substring() or slice() method (NN4+, IE4+), their specific usage is explained below.
The prototype of substring() is: string.substring(from, to)
The first parameter from specifies the starting position of the substring in the original string (0-based index); the second parameter to is optional. It specifies the end position of the substring in the original string (0-based index). Generally, it should be larger than from. If it is omitted, the substring will go all the way to the original string. at the end.
What will happen if the parameter from is accidentally larger than the parameter to? JavaScript will automatically adjust the starting and ending positions of the substring, that is, substring() always starts from the smaller of the two parameters and ends with the larger one. Note, however, that it includes the character at the starting position, but not 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 parameter start represents the starting position of the substring. If it is a negative number, then it can It is understood as the number from the bottom to the beginning, for example -3 means starting from the third from the bottom; the parameter end indicates the end position. Like start, it can also be a negative number, and its meaning also means the number from the bottom to the end. The parameters of slice() can be negative numbers, so it is more flexible than substring(), but less tolerant. If start is larger than end, it will return an empty string (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 represents the starting position, and length represents the substring. length. The JavaScript standard discourages the use of this method.
5. String case conversion
Question:
There is a text box on your page to receive user input information, such as city, and then you will do different processing according to his city. String comparison will naturally be used at this time, so before comparison, it is best to perform case conversion, so that you only need to consider the situation after conversion; or you need to collect data on the page, and then store the data in the database, and the database It happens to only accept uppercase characters; in these cases we all have to consider case conversion of the string.
Solution:
Use toLowerCase() and toUpperCase() methods:

var city = "ShanGHai";
city = city.toLowerCase(); // city is "shanghai" now.

Determine whether two strings are equal
Problem:
For example, you want to compare the user's input value with a known string
Solution:
First convert all user input values ​​​​to uppercase (or lowercase), and then run Compare:

var name = document.form1.txtUserName.value.toLowerCase();
if(name == "urname")
{
// statements go here.
}

JavaScript has two equality operators. One is fully backward compatible, standard "==". If the two operand types are inconsistent, it will automatically perform type conversion on the operand at some point. 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 have different data types. The former is string, and the latter is object. When using the "==" operator, JavaScript will try various evaluations to detect whether the two will be equal under certain circumstances. So the following expression evaluates to true: strA == strB.
The second operator is the "strict" "===", which is not so forgiving during evaluation and does not perform type conversion. So the expression strA === strB evaluates to false, although both variables hold the same value.
Sometimes the logic of the code requires you to determine whether two values ​​​​are not equal. There are also two options here: "!=" and strict "!==". Their relationship is similar to "==" and "==" =".
Discussion:
"==" and "!=" will try their best to find value matching when evaluating, but you may still want to perform explicit type conversion before comparison to "help" They get the job done. 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) { . .. }
You can also convert in advance:
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 the program.

There is one situation that needs to be paid attention to, which is the regional settings of the computer. If you use "<" and ">" to compare strings, then JavaScript compares them as Unicode, but obviously people browsing the web don't read text as Unicode :) For example in Spanish, According to traditional sorting, "ch" will be sorted as a character between "c" and "d". localeCompare() provides a way to use the character collation of the default locale.

var strings; // The string array to be sorted, assuming it has been initialized
strings.sort(function(a,b) { return a.localeCompare(b) }); / / Call the sort() method to sort

Searching for strings

Question:
Determine whether a string contains another string.
Solution:
Use the indexOf() method of string:
strObj.indexOf(subString[, startIndex])
strObj is the string to be judged, subString is the substring to be found in strObj String, startIndex is optional, indicating the starting position of the search (0-based index). If startIndex is omitted, the search starts from the beginning of strObj. If startIndex is less than 0, it starts from 0. If startIndex is greater than the maximum index, it starts from Start at the maximum index.
indexOf() returns the starting position of subString in strObj. If it is not found, it returns -1. In the script, you can use it like this:

iF (LargetRing.indexof (Shortstring)! = --1)
{
// If it is included, process it accordingly;
}

##String length

You can use the built-in property length to calculate the length of a string:

  var txt = "Hello World!";
document.write("" + txt.length + "");
var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write("" + txt.length + "");
Next Section
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p id="demo"></p> <script> var x = "John"; // x 是字符串 var y = new String("John"); // y 是一个对象 document.getElementById("demo").innerHTML = x===y; </script> <p>=== 为绝对相等,即数据类型与值都必须相等。</p> </body> </html>
submitReset Code
ChapterCourseware