Home  >  Article  >  Web Front-end  >  Example: Use JavaScript to operate strings (some string functions)_Basic knowledge

Example: Use JavaScript to operate strings (some string functions)_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 19:19:02982browse

Manipulating string values ​​is a daily routine that the average developer must face. There are many specific ways to manipulate strings, 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 functionality they need:

 • concat() – Concatenates two or more characters of text and returns a new string.

  • indexOf() – Returns the index of the first occurrence of a substring in a string. If there is no match, -1 is returned.

  • charAT() – Returns the character at the specified position.

 • lastIndexOf() – Returns the index of the last occurrence of a substring in the string. If there is no match, returns -1.

 • match() – Checks whether a string matches a regular expression.

  • substring() – Returns a substring of a string. The incoming parameters are the starting position and the ending position.

 • replace() – Used to find a string that matches a regular expression, and then replace the matching string with a new string.

  • search() – performs a regular expression matching search. If the search is successful, the matching index value in the string is returned. Otherwise, -1 is returned.

  • slice() – extracts a portion of a string and returns a new string.

  • split() – Convert a string into a string array by dividing the string into substrings.

  • length() – Returns the length of the string. The length of the string refers to the number of characters it contains.

  • toLowerCase() – Converts the entire string to lowercase letters.

  • toUpperCase() – Converts the entire string to uppercase letters.

Note: The concat , match , replace and search functions were added in JavaScript 1.2. All other functions have been provided in JavaScript 1.0.

Let’s take a look at how to use these functions in JavaScript.下面的代码是用到了前面提到的所有函数:

 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()); 


  下面是执行上面的代码得到的结果:

  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

  示例代码把所有这些提到的函数都用到了。

  特殊字符

  除了这些函数之外,还有很多的特殊字符可以用来表示关键的效果。这些特殊字符包括:

  • t – 跳格键

  • b – 退格 / 删除

  • r – 回车

  • n – 换行

  • f – 换页

  特殊字符最常见的用途就是格式化输出。例如,你可能需要在输出中插入一个换行来正确地显示一个值。而且,在换行时也需要回车。在一些平台上,“ n ”已经足够产生换行效果了,而在一些机器上要正确地显示一个换行则需要“ rn ”。The following example shows special characters displayed on a multi-line 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 used 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; on the contrary, the method we use here simply expands the original value without requiring a new variable. Also, the example uses escape characters to display special characters correctly. The system interprets a backslash as a signal that it will be followed by a special character, but two backslashes negate this operation. Each character in the output is displayed on a new line using the newline special character.
Add to Toolbox
Special characters and functions can be combined with other JavaScript techniques to solve many problems. One such case is for JavaScript client-side form validation, and the method proposed in this article can be easily used to implement form validation.
The following code will be called when a form is submitted. The form to be submitted contains three fields: name, address, and zip code. To keep things simple, we just verify that each field cannot be empty and that the zip code must be numeric. The following JavaScript code accomplishes 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 missingn";
10
11}
12
13 if (doc.Address.value == "") {
14
15 msg = "- Address is missingn";
16
17 }
18
19 if (doc.ZipCode.value == "") {
20
21 msg = "- Zip code is missingn";
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:nn" msg;
40 alert(msg);
42
43}
45
46
47
In user This function is called when the form is submitted. The call to the function is implemented in the onSubmit event of an HTML button.



The validation function checks whether each field is empty. If a null value is found, an error message is appended to the validation message variable msg. Additionally, a regular expression is used to validate the format of the zip code field. Here, we only accept five-digit US zip codes. If any errors are found (i.e. 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.이는 웹 인터페이스의 비연결적 특성을 완벽하게 보완하므로 웹 서버와 상호 작용하지 않고도 많은 클라이언트 측 작업을 완료할 수 있습니다.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn