Script instance: manipulating strings with JavaScript

Source: Internet
Author: User
Tags contains empty expression functions split variable zip domain
javascript| Script | string

Although JavaScript has many uses, processing strings is one of the most popular. Let's take a closer look at the use of JavaScript to manipulate strings. In JavaScript, a String is an object. String objects are not stored as character arrays, so we must manipulate their values using built-in functions. These built-in functions provide a different way to access the contents of a string variable. Let's take a look at these functions in detail.

  Comprehensive

The value of an action string is a common occurrence that a typical developer must face. There are many ways to manipulate strings, such as extracting a portion from a string, or determining whether a string contains a particular character. The following JavaScript functions provide developers with all the functionality they need:

concat () – Combines the text of two or more characters to return a new string.

indexof () – returns the index at the first occurrence of a substring in a string. If there is no match, return-1.

charat () – returns the character at the specified position.

LastIndexOf () – Returns the index of the last occurrence of a substring in a string, or 1 if there are no matches.

Match () – checks whether a string matches a regular expression.

substring () – Returns a substring of the string. Incoming parameters are the starting and ending positions.

replace () – Used to find a string that matches a regular expression, and then use a new string instead of a matching string.

Search () – performs a regular expression matching lookup. Returns the matching index value in the string if the lookup succeeds. otherwise return-1.

Slice () – Extracts part of the string and returns a new string.

Split () – Makes a string array of strings by dividing the strings into substrings.

Length () – Returns the length of the string, so that the length of the 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 in JavaScript 1.2. All other functions are already available in JavaScript 1.0.

Now let's take a look at how these functions are used in JavaScript. The following code uses all of the functions mentioned earlier:

function manipulatestring (passedString1, passedString2) {
var concatstring;
The string passed to Concat are added to the "end of" the
concatstring = Passedstring1.concat (passedString2);
alert (concatstring);
The following if statement'll be true since-a-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
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 code above:

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 example code uses all of these mentioned functions.

Special characters

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

\t– Tab

\b– BACKSPACE/delete

\r– Carriage return

\n– Line Change

\f– Page Change

The most common use of special characters is to format the output. For example, you might want to insert a newline in the output to correctly display a value. Also, carriage returns are required when changing rows. On some platforms, "\ n" is sufficient to produce a wrapping effect, and on some machines it is necessary to properly display a line break. The following example shows the special characters displayed on 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);
The previous example uses the plus sign to concatenate strings without using the concat function. The reason is simple, for the concat function, each operation requires a new variable; instead, the method we use here simply expands the original value without the need for a new variable. Also, the example uses a newline character to display special characters correctly. The system treats a backslash as a signal that it will be followed by a special character, but it is offset by a two backslash. Each character in the output is displayed in a new row by newline special characters.
Add to Toolbox
Special characters and functions can be combined with other JavaScript techniques to solve many problems. One such scenario is used for JavaScript client form validation, and the method presented in this article can be used simply to implement form validation.
The following code is invoked when a form is submitted. The form to submit contains three fields: Name, address, and postal code. To make this easier, we only verify that each domain cannot be empty and that 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
if (Doc. Address.value = = "") {
14
msg + = "-Address is missing\n";
16
17}
18
if (Doc. Zipcode.value = = "") {
20
msg = "-Zip code is missing\n";
22
23}
24
var zip = new String (Doc. Zipcode.value);
26
if (Zip.search (/^[0-9][0-9][0-9][0-9][0-9]$/) ==-1) {
28
msg + = "-Enter valid ZIP code";
30
31}
32
if (msg = = "") {
34
Doc.submit;
36
Notoginseng} else {
38
msg = "Please correct the following validation errors and re-submit:\n\n" + msg;
40
Alert (msg);
42
43}
44
45}
46
47

This function is invoked when the user submits the form. A call to a function is implemented in the OnSubmit event of an HTML button.

<input type= "button" type= "Submit" value= "Submit" >

The validation function checks whether each domain is empty. If a null value is found, an error message is added after the message variable MSG is validated. In addition, a regular expression is used to verify the format of the ZIP Code field. Here, we only accept the five-digit zip code in the US area. If any errors are found (that is, the MSG variable is not empty), the program displays an error message, otherwise the program submits the form.

  A powerful language.

JavaScript has matured into a full-featured language that can be used to build powerful applications. It is a perfect complement to a web interface with a connectionless nature that allows many client operations to be done 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.