Home  >  Article  >  Web Front-end  >  Detailed explanation of string operations in JavaScript_javascript skills

Detailed explanation of string operations in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:15:53937browse

1. Overview
Strings are almost everywhere in JavaScript. When you process user input data, when you read or set the properties of a DOM object, when you operate cookies, and of course there are 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.

2. 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 enclose the string, but be aware that the pair of quotes that delimit the string must be the same and cannot be mixed.
A declaration like var myString = "Fluffy is a pretty cat.'; is illegal.
Allows the use of two kinds of quotation marks, making certain operations simple, such as embedding one into the other:

Copy code The code is as follows:

document.write("Logo");

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!");
Using the typeof operator, you will find that the myStr type above is string, and the strObj type is object.

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

3. String concatenation
Problem:
Splicing two or more strings into one large string
Solution:
Very simple, just use a " " to "Add" two strings:

Copy code The code is as follows:

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

To accumulate multiple strings into one string, you can also use the " =" operator:
Copy code The code is as follows:

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

To add a newline character to the string, you need to use the escape character "n":
Copy code The code is as follows:

var confirmString = "You did not enter a response to the last "
"question.nnSubmit 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 , is invalid, replace it with "
":

Copy code The code is as follows:
 
var htmlString = "First line of string.document.write(htmlString);

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

4. Accessing substrings of strings
Question:
Obtain 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.

Copy code The code is as follows:

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, it can be understood as the number from the last to the beginning. For example, -3 means starting from The third from the bottom starts; the parameter end represents the end position. Like start, it can also be a negative number, and its meaning also indicates the end of the penultimate position. The parameters of slice() can be negative, 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(), whose prototype is: string.substr(start, length)
From the prototype, you 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
Problem:
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 that only uppercase characters are accepted; in these cases we all need to consider case conversion of the string.
Solution:
Use toLowerCase() and toUpperCase() methods:

Copy code The code is as follows:

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

6. Determine two strings Is it 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), Then compare:

Copy code The code is as follows:

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

JavaScript has two equality operators. One is completely backward compatible, the 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:

Copy code The code is as follows:

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 both 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 when evaluating 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 thing you need to pay attention to, which is the computer’s regional settings. 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.

Copy code The code is as follows:

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

7. 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, search from the beginning of strObj, if startIndex is less than 0, then start from 0, if startIndex is greater than the maximum index, then search from Start at the maximum index.
indexOf() returns the starting position of subString in strObj, if not found, returns -1. In a script, you can use it like this:

Copy the code The code is as follows:

if(largeString. indexOf(shortString) != -1)
{
// If included, process accordingly;
}

Maybe a string will contain another string more than once , then the second parameter startIndex may come in handy. The following function demonstrates how to find the number of times a string contains another string:

Copy code The code is as follows:

function countInstances(mainStr, subStr)
{
var count = 0;
var offset = 0;
do
{
offset = mainStr.indexOf(subStr, offset);
if(offset != -1)
                                                                                                                                                                     ;
}


String object has a method corresponding to indexOf(), lastIndexOf():
strObj.lastIndexOf(substring[, startindex])
strObj is the string to be judged, subString is to be searched in strObj substring, startIndex is optional, indicating the starting position of the search (0-based index), if startIndex is omitted, search from the end of strObj, if startIndex is less than 0, start from 0, if startIndex is greater than the maximum index, Then start from the maximum index. This method searches from right to left and returns the last position of subString in strObj. If it is not found, it returns -1.

8. Convert between Unicode values ​​and characters in strings
Question:
Obtain the Unicode encoding value of a character and vice versa.
Solution:
To obtain the Unicode encoding of a character, you can use the string.charCodeAt(index) method, which is defined as:
strObj.charCodeAt(index)
index is the specified character in the strObj object position (0-based index), 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

If there is no character at the index specified by index, 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, which means you do not need to create a string instance before use:
String. fromCharCode(c1, c2, ...)
It accepts 0 or more integers and returns a string that contains the characters specified by each parameter, for example:

Copy code The code is as follows:

var str = String.fromCharCode(72, 101, 108, 108, 111); // str = = "Hello"

Discussion:
Unicode contains character sets for many writing languages ​​in the world, but don’t expect that just because Unicode contains a character, this character can be used in warning dialog boxes and text boxes. Or display normally when the page is rendered. If the character set is not available, it will appear on the page 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 Chinese character set and its fonts are installed.

Reference:
JavaScript And Dhtml Cookbook(Oreilly) ;
JavaScript-The Definitive Guide(4th Edition);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Introduction to for..in loop traps in JavaScript_javascript tipsNext article:Introduction to for..in loop traps in JavaScript_javascript tips

Related articles

See more