JavaScript Instance Tutorial (18) using String functions

Source: Internet
Author: User
Tags add format empty end functions string string methods variable
javascript| Functions | tutorials | strings

String functions that use JavaScript

String objects provide many methods, but few programmers make the most of them, which, for a programmer, cannot be said to be a flaw. Strings provide methods that can be used to manipulate characters, produce HTML tags, search strings, and so on.

Let's begin by saying what a string is. In the JavaScript language, a string is an object. As in Java, they are not stored as a series of characters, so the operation of strings must be done using built-in constructors and setup functions. In later versions, there were string constructors and more concepts about objects. At this level, a string is a variable consisting of a letter rather than a number, which is the concept of a string.

For instance, 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, and this length returns the number of characters in the string.

The most commonly used string methods are: IndexOf (), CharAt (), and substring (). Because these methods often appear in JavaScript, I'll explain them in more detail here:

IndexOf () function

This function allows you to determine whether a string exists in a longer string and where it is located. It is equivalent to the STRSTR function in C language and the InStr function in the Visual Basic language. This method also has a corresponding function: LastIndexOf (), the other end of this function string search.

As the name of the function implies, the return value indicates the position of the string in the searched string. Returns 1 if the string you are searching for is not found in the string being searched. Notice here that in JavaScript-1 is a normal integer, not a Boolean (Boolen) number. Here is a concrete example:

var myString = "Have a nice day!";

Alert (Mystring.indexof ("a")); file:// , return 1.

Alert (Mystring.lastindexof ("a")); Here return 13

Again, the index of an array in JavaScript starts at 0, and the C language is the last words. So the above statement alert (Mystring.indexof ("a")) is returned 1 because "a" is in the string "Have a nice day!" The second position.

Be careful, you may find the string "Have a nice day!" There is also a character "a", how can you find the second letter "a"? This is a good question, in order to do this, we have to introduce the second parameter of the function. The second argument is an integer that indicates where the search begins in the string.

To synthesize the above knowledge, the following code to find all the characters "a", the specific code is as follows:

var myString = "Have a nice day!";

var index = Mystring.indexof ("a");

while (index!=-1) {

alert (index);

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

}

Here's a detailed explanation of the code: the variable index is initialized to the location of the first "a" (if there is no "a", then the variable index is-1). And then give a loop, the condition is index!=-1. In each loop, we add the variable index to 1, starting with the first character after "a" found, until all the characters "a" are found. When no more character "a" in the string variable mysring found in the return-1 value, this time the index is equal to 1, does not meet the cyclic conditions index!=-1, so that the end of the cycle. And the output of Alert (index) statement is: 1,5,13.

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

CharAt () function

This function returns the character at the given position in the string. In essence, it is a special case of the substring () method, but it also has its own purpose. If you were a C-language programmer or a programmer in a similar language, you would understand that when you refer to a character, you can use String.charat (index) instead of String[index].

Now let's use this function in a form input. The form has an email address, of course, the email address to be limited to characters, numbers and a "@" symbol. We can do this one at a a single character to enforce the string. The detailed code is as follows:

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

var parsed = true;

var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-";

var email = prompt ("What is your e-mail 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)

As shown in Figure 1. You can press the Check Email button and a dialog box pops up, as shown in Figure 2.

(Figure 2)

You can fill in an email address and click OK. A result of checking the email address will also pop up. Join you enter email address: Afterpurple@pconline.com.cn , you will see the result as shown in Figure 3. If you enter: Ok#pconline.com.cn will appear as shown in Figure 4, because # is an invalid character.

(Figure 3)

(Figure 4)

The above code is explained in detail below:

The examples above use a number of string functions, circular statements, and Boolean (Boolean) operations. All of these are mentioned in the previous tutorial, except, of course, the toLowerCase () function, which is described below.

The above code is actually very simple, just want to test the email address of each character is not a valid character just. But the implementation process looks a bit clumsy, not as simple as C or Perl. Essentially, we use Charat () to iterate through the string of email addresses to extract invalid characters.

If the character is valid, continue looping; If the character is invalid, a warning window will pop up stating that the character is invalid, and then use the break statement to end the For loop after setting Parsed=false.

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


SUBSTRING () function

This function is usually used to extract any part of the 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 return part. You may sound foggy, but one of the best ways to memorize it is to return a string of length equal to End-start.

If the second argument is omitted, it defaults to the end of the string. Here are a few examples:

var str = "This is a string";

Str.substring (1, 3); file:// fruit for hi

Str.substring (3, 1); file:// fruit for hi

Str.substring (0, 4); file:// Fruit for this

Str.substring (8); file:// fruit for hi

Str.substring (8, 8); file:// Fruit is empty

The second example above shows that when Start>end, the two parameters are automatically converted. The final example shows that when start equals end, the return value is an empty string.

Character Format (HTML)

The least-used functions in JavaScript are described below. Although they are not very useful, at least they add some decoration to your code. These methods create HTML code from character objects to be displayed on a 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</smal>

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 related to HTML-specific, but they are useful as a format tool. All of these methods can be applied to a string to create a custom format.

Here's another example: <BODY>

<script language= "JavaScript" >

<!--Hide from older browsers

var heading = prompt ("Please enter a heading", "Test heading");

var colour = prompt ("Please enter a colour", "darkred");

document.write (Heading.fontsize (7). FontColor
(colour). Bold (). toUpperCase ());

Stop hiding-->

</SCRIPT>

</BODY>

(Figure 5)

When you press the button shown in Figure 5, you can pop up a dialog box like Figure 6:

(Figure 6)

Enter the title of the page in the box: Pacific Internet, click OK. Then a dialog box pops up asking for a color, as shown in Figure 7:

(Figure 7)

Clicking on the OK key results in the following page as shown in Figure 8:

(Figure 8)

As we explained earlier, it is impossible to write something to a loaded document or window. To display this code we open a new window and write the resulting HTML code for the window.

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

Escape () and unescape ()

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

Http://www.mydomain.com.au/index.html?name=Duncan%20Crombie

The Web server and Web browser can only handle a limited number of characters, so any character that exceeds this range will be passed in digital form.

This escape function encodes variables, which are used frequently when cookies are set, and unescape functions are used to decode them.





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.