Home > Web Front-end > JS Tutorial > String operations in JavaScript

String operations in JavaScript

高洛峰
Release: 2016-11-26 16:04:50
Original
1200 people have browsed it

String operations in JavaScript

1. Overview

Strings are almost everywhere in JavaScript. When you process user input data, when you read or set the attributes of DOM objects, when you operate cookies, Of course there is more…. The core part of JavaScript provides a set of properties and methods for common string operations, such as splitting strings, changing the case of strings, operating substrings, etc.

Most current browsers can also benefit from the power of regular expressions, as it greatly simplifies a large number of string manipulation tasks, but it also requires you to overcome a somewhat steep learning curve. Here, we mainly introduce some operations on the string itself. Regular expressions will be covered in future essays.

2. Creation of String

There are several ways to create a string. The simplest is to enclose a set of characters in quotes, which can be assigned to a string variable.

var myStr = "Hello, String!";

You can use double quotes or single quotes to include the string, but be aware that the pair of quotes that delimit the string must be the same and cannot be mixed.

A statement like var myString = "Fluffy is a pretty cat.'; is illegal.

Allows the use of two types of quotes, making certain operations simple, such as embedding one into the other:

document.write("Logo");

We created it in the above script Several strings, but essentially, they are not real string objects. To be precise, they are values ​​of string type. To create a string object, use the following statement: var strObj = new String("Hello. , String!");

Use the typeof operator to check and you will find that the myStr type above is string, and the strObj type is object.

If you want to know the length of the string, use its length attribute: string.length.

Method to get the characters at the specified position of the string: string.charAt(index); String

solution:

Very simple, just use a "+" to "add" the two strings:

var longString = "One piece " + "plus one more piece.";

To accumulate multiple strings into one string, you can also use the "+=" operator:

var result = "";

result += "My name is Anders"

result += " and my age is 25";

To add a newline character to the string, you need to use the escape character "n":

var confirmString = "You did not enter a response to the last " +

"question.nnSubmit form anyway?";

var confirmValue = confirm(confirmString);

But this method can only be used in situations like warnings and confirmation dialog boxes. If this text is used as HTML When the content is displayed, it will be invalid. Replace it with "
":

var htmlString = "First line of string.
Second line of string.";

document.write (htmlString);

The String object also provides the method concat(), which performs the same function as "+":

string.concat(value1, value2, ...)

But concat() The method is obviously not as intuitive and concise as "+".

4. Accessing substrings of strings

Question:

Obtain a copy of a part of a string.

Solution:

Use substring() or slice() method (NN4+, IE4+), their specific usage is explained below.

The prototype of substring() is: string.substring(from, to)

The first parameter from specifies the starting position of the substring in the original string (0-based index); the second parameter to is Optional, it specifies the end position of the substring in the original string (0-based index). Generally, it should be larger than from. If it is omitted, the substring will continue to the end of the original string. at.

What happens if the parameter from is accidentally larger than the parameter to? JavaScript will automatically adjust the starting and ending positions of the substring, that is, substring() always starts from the smaller of the two parameters and ends with the larger one. Note, however, that it includes the character at the starting position, but not the character at the ending position.

var fullString = "Every dog ​​has his day.";

var section = fullString.substring(0, 4); // section is "Ever".

section = fullString.substring(4, 0); // section is also "Ever".

section = fullString.substring(1, 1); // section is an empty string.

section = fullString.substring( -2, 4); // section is "Ever", same as fullString.substring(0, 4);

The prototype of slice() is: string.slice(start, end)

Parameter start Indicates the starting position of the substring. If it is a negative number, it can be understood as the starting position from the last to last. For example, -3 means starting from the third from the last. The parameter end indicates the end position. Like start, it can also be a negative number. The meaning also indicates the end of the penultimate number. The parameters of slice() can be negative, so it is more flexible than substring(), but less tolerant. If start is larger than end, it will return an empty string (example omitted).

Another method is substr(), whose prototype is: string.substr(start, length)

From the prototype, we can see the meaning of its parameters. start represents the starting position, and length represents the length of the substring. . The JavaScript standard discourages the use of this method.

5. String case conversion

Question:

There is a text box on your page to receive user input information, such as city, and then you will do different processing according to his city. At this time, naturally String comparison will be used, so before comparison, it is best to perform case conversion, so that you only need to consider the situation after conversion; or you need to collect data on the page and then store the data in the database, and the database happens to only receive uppercase characters; in these cases we all need to consider case conversion of the string.

Solution:

Use toLowerCase() and toUpperCase() methods:

var city = "ShanGHai";

city = city.toLowerCase(); // city is "shanghai" now.

6. Determine whether two strings are equal

Problem:

For example, you want to compare the user’s input value with a known string

Solution:

First convert all user input values ​​to uppercase ( or lowercase), and then compare:

var name = document.form1.txtUserName.value.toLowerCase();

if(name == "urname")

{

              // statements go here.

}

JavaScript has two equality operators. One is completely backward compatible, standard "==". If the two operand types are inconsistent, it will automatically perform type conversion on the operand at some point. Consider the following assignment statement:

var strA = "i love you!";

var strB = new String("i love you!");

These two variables contain the same character sequence, but have different data types. The former is string. The latter is object. When using the "==" operator, JavaScript will try various evaluations to detect whether the two will be equal under certain circumstances. So the following expression evaluates to true: strA == strB.

The second operator is the "strict" "===", which is not so forgiving during evaluation and does not perform type conversion. So the expression strA === strB evaluates to false, although both variables hold the same value.

Sometimes the logic of the code requires you to determine whether two values ​​​​are not equal. There are also two options here: "!=" and strict "!==". Their relationship is similar to "==" and "===" ".

Discussion:

"==" and "!=" will try their best to find value matching when evaluating, but you may still want to perform explicit type conversion before comparison to "help" them complete Work. For example, if you want to determine whether a user's input value (string) is equal to a number, you can let "==" help you complete the type conversion:

if(document.form1.txtAge.value == someNumericVar) { .. . }

You can also convert in advance:

if(parseInt(document.form1.txtAge.value) == someNumericVar) { ... }

If you are more accustomed to strongly typed programming languages ​​(such as C#, Java, etc. ), then you can continue your habit (type conversion) here, which will also enhance the readability of the program.

There is one thing that needs to be paid attention to, which is the regional settings of the computer. If you use "<" and ">" to compare strings, then JavaScript compares them as Unicode, but obviously people browsing the web don't read the text as Unicode :) For example in Spanish, According to traditional sorting, "ch" will be sorted as a character between "c" and "d". localeCompare() provides a way to use the character collation of the default locale.

var strings; // The string array to be sorted, assuming it has been initialized

strings.sort(function(a,b) { return a.localeCompare(b) }); // Call the sort() method to sort

7. Searching for strings

Question:

Judgment Whether a string contains another string.

Solution:

Use the indexOf() method of string:

strObj.indexOf(subString[, startIndex])

strObj is the string to be judged, subString is the substring to be found in strObj, startIndex It is optional and indicates the starting position of the search (0-based index). If startIndex is omitted, the search will start from the beginning of strObj. If startIndex is less than 0, it will start from 0. If startIndex is greater than the maximum index, it will start from the maximum index. .

IndexOf() returns the starting position of subString in strObj. If it is not found, it returns -1. In a script, you can use it like this:

if(largeString.indexOf(shortString) != -1)

                                                                                                                                                   ​will contain another string more than once, in which case the second parameter startIndex may come in handy. The following function demonstrates how to find the number of times a string contains another string:

function countInstances( mainStr, subStr)

                                                                                               var count = 0; , offset);

if(offset != -1) U {

Count ++;

Offset+= Substr.Length;

}} While (Office! = -1)

Return Count; () corresponding method, lastIndexOf():

strObj.lastIndexOf(substring[, startindex])

strObj is the string to be judged, subString is the substring to be searched in strObj, startIndex is optional, Represents the starting position of the search (0-based index). If startIndex is omitted, the search is from the end of strObj. If startIndex is less than 0, it starts from 0. If startIndex is greater than the maximum index, it starts from the maximum index. This method searches from right to left and returns the last occurrence of subString in strObj. If it is not found, it returns -1.

8. Convert between Unicode values ​​and characters in strings

Question:

Get the Unicode encoding value of a character and vice versa.

Solution:

To obtain the Unicode encoding of a character, you can use the string.charCodeAt(index) method, which is defined as:

strObj.charCodeAt(index)

index is the position of the specified character in the strObj object (based on index of 0), the return value is a 16-bit integer between 0 and 65535. For example:

var strObj = "ABCDEFG";

var code = strObj.charCodeAt(2); // Unicode value of character 'C' is 67

If there is no character at the index specified by index, then The return value is NaN.

To convert the Unicode encoding to a character, use the String.fromCharCode() method. Note that it is a "static method" of the String object, which means there is no need to create a string instance before use:

String. fromCharCode(c1, c2, ...)

It accepts 0 or more integers and returns a string that contains the characters specified by each parameter, for example:

var str = String.fromCharCode( 72, 101, 108, 108, 111); // str == "Hello"

Discussion:

Unicode contains the character sets of many written languages ​​in the world, but don't expect this just because Unicode contains one character Characters display properly when rendering in alert dialogs, text boxes, or pages. If the character set is not available, it will appear on the page as a question mark or other symbol. A typical North American computer will not be able to display Chinese characters on the screen unless the Chinese character set and its fonts are installed.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template