Summary of string processing functions in Javascript

Source: Internet
Author: User
Tags string methods

String objects provide many methods, but few programmers make full use of them, which is a defect for a programmer. The methods provided by the string can be used to operate characters, generate HTML tags, and search strings.

The following describes what a string is. In JavaScript, a string is an object. As in Java, they are not stored as a series of characters, so string operations must be completed using the built-in constructor and setting functions. In later versions, there were a string constructor and more concepts about objects. At this level, a string is a variable consisting of letters rather than digits. This is the concept of a string.

For example, some valid strings are "hello", "Bob", "bob2", "33", "33.3", and 33 or 33.3 are not strings. All strings have a common attribute called length, which returns the number of characters in the string.

The most common string methods are indexof (), charat (), and substring (). These methods often appear in Javascript, so I will describe them in detail below:

Indexof () function

This function allows you to determine whether a string exists in a longer string and its location. It is equivalent to the strstr function in C language and the instr function in Visual Basic language. This method also has a corresponding function: lastindexof (), which is searched at the other end of the function string.

As the function name means, the return value indicates the position of the string in the searched string. If no string is found in the searched string,-1 is returned. In JavaScript,-1 is a normal integer, not a Boolean number. The following is an example:

VaR mystring = "have a nice day! ";

Alert (mystring. indexof ("A"); // here 1 is returned

Alert (mystring. lastindexof ("A"); // 13 is returned here

Here, we also need to remind you that the index of the array in Javascript starts from 0, which is the last word of C language. Therefore, the preceding statement alert (mystring. indexof ("A") returns 1 because "A" is in the string "have a nice day! .

Be careful, you may find the string "have a nice day! "There is another character" A ". How can we find the second letter"? This is a good problem. To do this, we must introduce the second parameter of this function. The second parameter is an integer indicating the start position of the string.

In order to combine the above knowledge, the following code is used to find all the characters "A". The specific code is as follows:

VaR mystring = "have a nice day! ";

VaR Index = mystring. indexof ("");

While (index! =-1 ){

Alert (INDEX );

Index = mystring. indexof ("A", index + 1 );
// Start search after last match found

}

The code below explains in detail: the variable index is initialized to the location where the first "a" is located (if there is no "A", the variable index is-1 ). Then a loop is given, with the condition "index! =-1. In each loop, we add the variable index to 1, that is, starting with the first character after "a", until all the characters "A" are found. When no character "a" is found in the string variable mysring,-1 is returned. At this time, the index is equal to-1 and does not meet the cyclic Condition Index! =-1, so the loop ends. The output of the alert (INDEX) statement is:, 13.

In this example, we only show indexof () for a single character search. If you use this function frequently, you will find that it can search for any character or string.

Charat () function

This function returns the character in the string at the given position. Essentially, it is a special case of the substring () method, but it also has its own purpose. If you are a C-language programmer or a programmer in a similar language, you can understand that when referencing characters, you can use string. charat (INDEX) to replace string [Index].

Next we will use this function in a form input. The form contains an email address. Of course, this email address must contain characters, numbers, and a "@" symbol. We can force a single character in the string column. The Code is as follows:

<Script language = "JavaScript"> <! -- Hide from older browsers

VaR parsed = true;

VaR validchars = "abcdefghijklmnopqrstuvwxyz0123456789 @.-";

VaR email = prompt ("What is your email address? "," Nobody@nowhere.com ");

For (VAR I = 0; I <email. length; I ++ ){

VaR letter = Email. charat (I). tolowercase ();

If (validchars. indexof (letter )! =-1)

Continue;

Alert ("invalid character:" + letter );

Parsed = false;

Break;

}

If (parsed) Alert ("your email address contains all valid characters .");

// Stop hiding -->

</SCRIPT>

(Figure 1)

1. You can press the "check email" button. A dialog box is displayed, as shown in figure 2.

(Figure 2)

You can enter an email address and click "OK. Then a check email address is displayed. After adding your input email address: purple@pconline.com.cn, you will see the result 3. If you enter OK # pconline.com.cn, The result 4 is displayed, because # is an invalid character.

(Figure 3)

(Figure 4)

The above code is explained in detail below:

The preceding example uses some string functions, loop statements, and Boolean operations. All of these are mentioned in the previous tutorial. Of course, except for the tolowercase () function, this function will be introduced below.

The above code is actually very simple, just to test whether each character in the email address is a valid character. However, the implementation process looks a little clumsy, not as simple as the C or Perl language. Essentially, charat () is used to cyclically browse the string of the email address to extract invalid characters.

If the character is valid, the loop continues. If the character is invalid, a warning window is displayed, indicating that the character is invalid, at this time, use the break statement to end the for loop after setting parsed = false.

When the loop exists, we can check the mark parsed to see if email is valid. If parsed is true, the message is displayed.

Click here to go to the test page
Substring () function

This function is usually used to extract any part of a string. Its parameters are 'start' and 'end '. The starting value is the index of the first character, and the ending value is the index of the first character after the part is returned. You may feel confused, but the best way to remember this is to return a string with the length equal to end-start.

If the second parameter is omitted, It defaults to the end of the string. The following are examples:

VaR STR = "this is a string ";

Str. substring (1, 3); // The result is hi.

Str. substring (3, 1); // The result is hi.

Str. substring (0, 4); // The result is this

Str. substring (8); // The result is hi.

Str. substring (8, 8); // The result is null.

The second example above shows that when Start> end, the two parameters are automatically converted. The final example shows that when start is equal to end, the return value is a null string.

Character format (HTML)

The following describes the least used functions in JavaScript. Although they are not very useful, at least they add decoration to your code. These methods Create HTML code from the character object for display on the web page.

Str. Anchor ("anchor1 ")

<A name = "anchor1"> This is a string </a>

This is a string

Str. Big ()

<Big> This is a string </big>

This is a string

Str. Blink ()

<Blink> This is a string </blink>

This is a string

Str. Bold ()

<B> This is a string </B>

This is a string

Str. Fixed ()

<Tt> This is a string </tt>

This is a string

Str. fontcolor ("darkred ")

<Font color = "darkred"> This is a string </font>

This is a string

Str. fontsize (5)

<Font size = "5"> This is a string </font>

This is a string

Str. Italics ()

<I> This is a string </I>

This is a string

 

Str. Link ("index.html ")

<A href = "index.html"> This is a string </a>

This is a string

Str. Small ()

<Small> This is a string </small>

This is a string

Str. Strike ()

<Strike> This is a string </strike>

This is a string

Str. sub ()

<Sub> This is a string </sub>

This is a string

Str. Sup ()

<Sup> This is a string </sup>

This is a string

Str. tolowercase ()

This is a string

This is a string

Str. touppercase ()

This is a string

This is a string

The last two examples in the table above are not HTML-specific, but they are useful as a format tool. All of these methods can be applied to strings to create a custom format.
The following is an example: <body>

<Script language = "JavaScript">

<! -- Hide from older browsers

VaR heading = prompt ("Please enter a heading", "test heading ");

VaR color = prompt ("Please enter a color", "darkred ");

Document. Write (heading. fontsize (7). fontcolor
(Color). Bold (). touppercase ());

// Stop hiding -->

</SCRIPT>

</Body>

 

(Figure 5)

Press the button shown in 5 to bring up the 6 dialog box:

(Figure 6)

In the box, enter the web page title: Pacific computer network, and click OK. In the dialog box that appears, enter the color, as shown in figure 7:

(Figure 7)

Click OK to generate the page shown in Figure 8:

(Figure 8)

Click here to go to the test page

As we explained earlier, writing something to a mounted document or window is impossible. To display this code, we open a new window and write the generated HTML code to the window.

Of course, you can only use JavaScript to format the text, but once the formatted text appears on the webpage, it will not be changed.

Escape () and Unescape ()

When you pass a value from a web page to another web page, you can use the URL to search for a string (for example, using a form, using method = "get "), at this time, you will find that some characters are converted to % NN format:

Http://www.mydomain.com.au/index.html? Name = Duncan % 20 crombi

The network server and Web browser can only process limited characters, so any character beyond this range will be passed in the form of numbers.

This escape function can encode variables, which are frequently used when cookies are set. The Unescape function is used to decode them.

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.