JS operation string

Source: Internet
Author: User
Although Javascript is useful, processing strings is one of the most popular. The following describes how to use JavaScript to operate strings. In JavaScript, string is an object. String objects are not stored as character arrays, so we must use built-in functions to manipulate their values. These built-in functions provide different methods to access the content of string variables. Let's take a closer look at these functions.


The value of the operation string 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 followingCodeAll the functions mentioned above are used:

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




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. Article The method proposed in 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 (){
3 var Doc = Document. Forms [0];
5 var MSG = "";
7 if (Doc. Name. value = ""){
9 MSG = "-name is missing \ n ";
13 if (Doc. Address. value = ""){
15 MSG = "-address is missing \ n ";
19 if (Doc. zipcode. value = ""){
21 MSG = "-zip code is missing \ n ";
25 var zip = new string (Doc. zipcode. value );
27 if (zip. search (/^ [0-9] [0-9] [0-9] [0-9] [0-9] $/) =-1 ){
29 MSG = "-enter valid zip code ";
33 If (MSG = ""){
35 Doc. Submit;
37} else {
39 MSG = "please correct the following validation errors and re-submit: \ n" MSG;
41 alert (MSG );

When a user submits a form, this function will be called. Function calls are implemented in the onsubmit event of an HTML button.

<Input type = "button" type = "Submit" value = "Submit" onclick = "validation ()">

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 ),ProgramAn error message is displayed. Otherwise, the program submits 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.

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.