Example: using JavaScript to operate strings (some string functions) _ basic knowledge

Source: Internet
Author: User
Example: using JavaScript to operate strings (some string functions) to operate string values is common for developers. There are many methods to operate on a string, such as extracting part of the content from a string or determining whether a string contains a specific character. The following JavaScript Functions provide developers with all the functions they need:

• Concat ()-combines two or more characters to return a new string.

• IndexOf ()-returns the index at the first part of a substring in a string. If no match exists,-1 is returned.

• CharAT ()-returns the character at the specified position.

• LastIndexOf ()-returns the index that appears at the end of a substring in a string. If no match exists,-1 is returned.

• Match ()-check whether a string matches a regular expression.

• Substring ()-returns a substring of a string. The input parameters are the start position and end position.

• Replace ()-used to find a string that matches a regular expression, and then use a new string to replace the matched string.

• Search ()-execute a regular expression to match the search results. If the search is successful, the matching index value in the string is returned. Otherwise,-1 is returned.

• Slice ()-extract a part of the string and return a new string.

• Split ()-divides a string into substrings to form a string array.

• Length ()-returns the length of a string. The so-called length of a string refers to the number of characters it contains.

• ToLowerCase ()-converts the entire string into lowercase letters.

• ToUpperCase ()-converts the entire string into uppercase letters.

Note: The concat, match, replace, and search functions are added to JavaScript 1.2. All other functions are provided in JavaScript 1.0.

Next let's take a look at how to use these functions in JavaScript. The following code uses all the functions mentioned above:

Function manipulateString (passedString1, passedString2 ){
Var concatString;
// The string passed to concat is added to the end of the first string
ConcatString = passedString1.concat (passedString2 );
Alert (concatString );
// The following if statement will be true since first word is Tony
If (concatString. charAt (3) = "y "){
Alert ("Character found! ");}
// The last position of the letter n is 10
Alert ("The last index of n is:" + concatString. lastIndexOf ("n "));
// A regular expression is used to locate and replace the substring
Var newString = concatString. replace (/Tony/gi, "General ");
// The following yields Please salute General Patton
Alert ("Please salute" + newString );
// The match function returns an array containing all matches found
MatchArray = concatString. match (/Tony/gi );
For (var I = 0; I
Alert ("Match found:" + matchArray [I]);
}
// Determine if the regular expression is found, a-1 indicates no
If (newString. search (/Tony/) =-1 ){
Alert ("String not found ");
} Else {
Alert ("String found .");
}
// Extract a portion of the string and store it in a new variable
Var sliceString = newString. slice (newString. indexOf ("l") + 2, newString. length );
Alert (sliceString );
// The split function creates a new array containing each value separated by a space
StringArray = concatString. split ("");
For (var I = 0; I
Alert (stringArray [I];
}
Alert (newString. toUpperCase ());
Alert (newString. toLowerCase ());
}

The following is the result of executing the above Code:

Tony Patton

Character Found!

The last index of n is: 10

Match found: Tony

Please salute General Patton

String not found

Patton

Tony

Patton

GENERAL PATTON

General patton

The sample code uses all the mentioned functions.

Special characters

In addition to these functions, there are many special characters that can be used to express key effects. These special characters include:

• \ T-hop key

• \ B-return/delete

• \ R-enter

• \ N-line feed

• \ F-form feed

The most common use of special characters is to format the output. For example, you may need to insert a line feed in the output to correctly display a value. In addition, you also need to press Enter when changing the line. On Some platforms, "\ n" is enough to generate a line feed, while "\ r \ n" is required to correctly display a line feed on some machines ". The following example shows the special characters displayed in a multiline window:


Var output = null;
Output = "Special Characters ";
Output + = "\ n ";
Output + = "==================== ";
Output + = "\ n ";
Output + = "\ t-tab ";
Output + = "\ n ";
Output + = "\ B-backspace/delete ";
Output + = "\ n ";
Output + = "\ r-carriage return ";
Output + = "\ n ";
Output + = "\ n-newline ";
Output + = "\ n ";
Output + = "\ f-form feed ";
Output + = "\ n ";
Alert (output );
In the preceding example, the plus sign is used to connect strings without the concat function. The reason is simple. For the concat function, each operation requires a new variable. On the contrary, the method we use here simply expands the original value without the new variable. In addition, the special characters are correctly displayed using the Escape Character in the example. The system regards a backslash as a signal and considers it to be followed by a special character, but the operation is offset by two backslashes. Each character in the output is displayed on the new line through the special newline character.
Add to toolbox
Special characters and functions can be combined with other JavaScript techniques to solve many problems. One of the cases is used for JavaScript client form verification. The method proposed in this article can be simply used for form verification.
The following code is called when a form is submitted. The form to be submitted contains three fields: name, address, and zip code. To achieve this, we only verify that each domain cannot be empty and the zip code must be a number. The following JavaScript code completes this function:
1 function validation (){
2
3 var doc = document. forms [0];
4
5 var msg = "";
6
7 if (doc. Name. value = ""){
8
9 msg + = "-Name is missing \ n ";
10
11}
12
13 if (doc. Address. value = ""){
14
15 msg + = "-Address is missing \ n ";
16
17}
18
19 if (doc. ZipCode. value = ""){
20
21 msg + = "-Zip code is missing \ n ";
22
23}
24
25 var zip = new String (doc. ZipCode. value );
26
27 if (zip. search (/^ [0-9] [0-9] [0-9] [0-9] [0-9] $/) =-1 ){
28
29 msg + = "-Enter valid Zip code ";
30
31}
32
33 if (msg = ""){
34
35 doc. submit;
36
37} else {
38
39 msg = "Please correct the following validation errors and re-submit: \ n" + msg;
40
41 alert (msg );
42
43}
44
45}
46
47
When a user submits a form, this function will be called. Function calls are implemented in the onSubmit event of an HTML button.



Verify the function to check whether each field is empty. If a null value is found, an error message is added after the message variable msg is verified. In addition, a regular expression is used to verify the format of the zip code domain. Here, we only accept the five-digit U.S. Postal code. If any error is found (that is, the msg variable is not empty), the program will display an error message; otherwise, the program will submit the form.

A powerful language

JavaScript has developed into a fully functional language that can be used to build powerful applications. It is a perfect complement to the Web interface with non-connectivity nature. It can complete many client operations without interacting with the Web server.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.