Encyclopedia of String Operations in JavaScript __java

Source: Internet
Author: User
Tags array length locale lowercase javascript array

JavaScript provides functions to find substrings in strings indexof (), LastIndexOf (), search (), and replacement functions for strings replace (), which are not implemented in array object array.

In order for array to support the above method, we can modify the Array object prototype and add the corresponding function. Let these functions have the same name as the functions of the string object and are similar in syntax to facilitate our use. Here are some simple introductions, and the reader can define other methods as needed.
//To determine if a string contains another string, substr: substring, start: Starting position
Array.prototype.indexof=function (substr,start) {var ta,rt,d= '/ 0 '; if (start!=null) {ta=this.slice (start); rt=start;} Else{ta=this;rt=0} var str=d+ta.join (d) +d,t=str.indexof (d+substr+d); if (t==-1) Return-1;rt+=str.slice (0,t). Replace (/[^/0]/g, '). length; return RT;
//This method looks up from right to left, returns the last occurrence of substr in Strobj, and returns-1 if it is not found.
Array.prototype.lastindexof=function (Substr,start) {var ta,rt,d= '/0 '; if (start!=null) {ta=this.slice (START); RT =start;} Else{ta=this;rt=0} ta=ta.reverse (); var str=d+ta.join (d) +d,t=str.indexof (d+substr+d); if (t==-1) Return-1;rt+=str.slice (t). replace (/[^/0]/g, '). Length-2; return RT;
//This method replaces the reg in the string as Rpby and is more commonly used.
Array.prototype.replace=function (reg,rpby) {var ta=this.slice (0), d= '/0 '; var str=ta.join (d); Str=str.replace ( REG,RPBY); Return Str.split (d); }

Looking for a specified substring in a string
Array.prototype.search=function (reg) {var ta=this.slice (0), d= '/0 ', Str=d+ta.join (d) +d,regstr=reg.tostring (); reg= New RegExp (Regstr.replace (///) (. | /n) +)//.*/g, '//0$1//0 '), Regstr.slice (Regstr.lastindexof ('/') +1)); T=str.search (reg); if (t==-1) Return-1;return Str.slice (0,t). Replace (/[^/0]/g, '). length; }

All of the above four methods are implemented to find or replace each element in the array, so that everyone does not have to do a cycle wasting time.
Second, JS operation of the string.

1, the creation of strings
There are several ways to create a string. The simplest is to enclose a set of characters in quotation marks and assign them to a string variable.
var mystr = "Hello, string!";
We created strings in the above script, but in essence they are not real string objects, and they are, to be exact, values of string types. To create a string object, you can use the following statement: var strobj = new String ("Hello, string!");
Use the typeof operator to see that the above mystr type is string and the Strobj type is object.
If you want to know the length of the string, use its Length property: String.Length.
Gets the character usage for the specified position of the string: String.charat (index);

2, String stitching
Very simply, "add" two strings with a "+":
var longstring = "One Piece" + "plus one more piece.";
To accumulate more than one string as a string, you can also use the "+ =" Operator:
var result = "";
result = "My name is Anders"
result = "And I Age is 25";
To add a line break in a string, you need to use the escape character "/n":
var confirmstring = "You did not enter a response to the" +
"Question./n/nsubmit form Anyway";
var confirmvalue = confirm (confirmstring);
However, this method can only be used in cases such as warning, confirmation dialog box, if this text is rendered as HTML content, it is invalid, and then replace it with "<br>":
var htmlstring = "A. String.<br>second line of String.";
document.write (htmlstring);

The string object also provides a method concat () that completes the same function as "+":
String.Concat (value1, value2, ...)
But Concat () method is obviously not as "+" come intuitive simplicity.

3, accessing substring of string
Using the substring () or slice () method (nn4+, ie4+), the specific use of them is described below.
The prototype of substring () is: string.substring (from, to)
The first argument from specifies the starting position of the substring in the original string (based on the 0 index); the second argument to is optional, which specifies the substring at the end of the original string (based on the 0 index), and generally, it should be larger than from, if it is omitted, The substring is then kept at the end of the original string.
What happens if the parameter from is not more careful than the argument to. JavaScript automatically mediates the start and end of a substring, which means that substring () always starts with the smaller of the two arguments, and ends with the larger one. Note, however, that it contains that character from the starting position, but does not contain the character at the end position.
var fullstring = "Every dog has his day."
var section = fullstring.substring (0, 4); The section is "Ever".

The prototype of Slice () is: String.slice (start, end)
The parameter start indicates the starting position of the substring and, if it is a negative number, it can be understood as the beginning of the penultimate, for example, 3, starting at the last third, and the argument end representing the ending position, which, like start, can also be negative, and its meaning to the penultimate end. The slice () parameter can be negative, so it is more flexible than substring (), but less forgiving, and if start is larger than end, it returns an empty string (example).
Another method is substr (), whose prototype is: String.substr (start, length)
From the prototype, you can see the meaning of its arguments, start represents the starting position, and length represents the substring. JavaScript standards do not encourage the use of this method.
4. Uppercase and lowercase conversions of strings
Use the toLowerCase () and toUpperCase () methods:
var city = "Shanghai";
City = City.tolowercase (); The city is the "Shanghai" now.
5, to determine whether two strings are equal
First convert the user's input value to uppercase (or lowercase), and then compare:
var name = Document.form1.txtUserName.value.toLowerCase ();
if (name = = "Urname")
Statements go.
JavaScript has two kinds of equality operators. One is completely backwards compatible, the standard "= =", if two operand types are inconsistent, it will automatically type the operand at some time, consider the following assignment statement:
var stra = "I love you!";
var strb = new String ("I love you!");
The two variables contain the same sequence of characters, but the data types are string, the latter is object, and when you use the "= =" operator, JavaScript tries various values to detect whether the two are equal in some case. So the following expression results in True:stra = = Strb.
The second operator is "strict" "= = =", it will not be so tolerant when the evaluation, will not be type conversion. So the value of the expression stra = = = Strb is 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 choices: "!=" and Strict "!==", their relationship is similar to "= =" and "= =".
"= =" and "!=" look for the matching of values as much as possible, but you might want to make explicit type conversions before you compare them to "help" them get the job done. For example, if you want to determine whether a user's input value (a string) equals 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.), you can extend your habits (type conversions) here, which will also enhance the readability of the program.

One thing to note is the locale of the computer. If you use "<" and ">" to compare strings, JavaScript compares them as Unicode, but it is clear that people do not read text as Unicode when browsing the Web: In Spanish, for example, in traditional order, "ch" will be ranked as a character between "C" and "D". Localecompare () provides a way to help you use character collation under the default locale.
var strings; An array of strings to sort, assuming that they have been initialized
Strings.sort (function (a,b) {return a.localecompare (b)}); Call the sort () method to sort

6, the search string
Use String's IndexOf () method:
Strobj.indexof (substring[, StartIndex])
Strobj is the string to be judged, substring is the substring to find in Strobj, startindex is optional, represents the starting position of the lookup (based on a 0 index), and if the startindex is omitted, it is found from the beginning of the strobj. If the startindex is less than 0, start at 0, and if startindex is greater than the maximum index, start at the maximum index.
IndexOf () returns the starting position of substring in strobj, or 1 if it is not found. In the script, you can use this:
if (Largestring.indexof (shortstring)!=-1)
If it is included, handle it accordingly;
Maybe a string will contain another string more than once, when the second argument startindex might come in handy, and the following function shows how to get the number of times a string contains another string:
function Countinstances (MAINSTR, SUBSTR)
var count = 0;
var offset = 0;
offset = mainstr.indexof (subStr, offset);
if (offset!=-1)
Offset + + substr.length;
}while (offset!=-1)
return count;
The string object has a method corresponding to the indexof (), LastIndexOf ():
Strobj.lastindexof (substring[, startindex])
Strobj is the string to be judged, substring is the substring to find in Strobj, startindex is optional, represents the starting position of the lookup (based on a 0 index), and if the startindex is omitted, the end of the strobj is found. If the startindex is less than 0, start at 0, and if startindex is greater than the maximum index, start at the maximum index. This method looks from right to left, returns the last occurrence of substring in strobj, and returns-1 if it is not found.

7. Converting between characters in Unicode values and strings
Gets the Unicode encoding value of one character, and vice versa.
To get Unicode encoding for 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 a 0 index), and returns a 16-bit integer value between 0 and 65535. For example:
var strobj = "ABCDEFG";
var code = strobj.charcodeat (2); Unicode value of character ' C ' is 67
The return value is Nan if there are no characters at the index specified by index.

To convert a Unicode encoding to a character, use the String.fromCharCode () method to note that it is a "static method" of a string object, meaning that you do not need to create a string instance before you use it:
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"
the operation of the JS array

1, the creation of the array

var arrayobj = new Array (); Create an array

var arrayobj = new Array ([size]); Create an array and specify the length, note not the upper limit, is the length

var arrayobj = new Array ([element0[, element1[, ...) [, ELEMENTN]]]); Create an array and assign a value

To illustrate, although the second method creates an array that specifies the length, in all cases the array is longer, that is, even if you specify a length of 5, you can still store the elements outside the specified length, note: the length changes.

2, access to elements of the array

var testgetarrvalue=arrayobj[1]; Gets the element value of an array

Arrayobj[1]= "This is the new value"; Give a new value to an array element

3, the addition of array elements

Arrayobj. Push ([Item1 [item2 [...] [Itemn]]]); /Adds one or more new elements to the end of the array and returns the new length of the array

Arrayobj.unshift ([Item1 [item2 [...] [Itemn]]]); /Adds one or more new elements to the beginning of the array, the elements in the array are automatically moved back, and the new length of the array is returned

Arrayobj.splice (insertpos,0,[item1[, item2[, ...) [, Itemn]]]); /inserts one or more new elements into the array at the specified position, and the element at the insertion point is automatically moved back to "".

4, the deletion of the elements of the array

Arrayobj.pop (); Removes the last element and returns the element value

Arrayobj.shift (); Removes the first element and returns the element value, and the elements in the array are automatically moved forward

Arrayobj.splice (Deletepos,deletecount); Deletes the specified number of DeleteCount elements starting at the specified position, deletepos the removed elements

5, the array of interception and merging

Arrayobj.slice (start, [end]); Returns a portion of an array as an array, noting that the end-corresponding element is not included, and if omitting the end copies all elements after start

Arrayobj.concat ([item1[, item2[, ...) [, Itemn]]]); Concatenate multiple arrays (or a string, or a mixture of arrays and strings) into an array, returning a new array of connections

6, the copy of the array

Arrayobj.slice (0); Returns an array of copies, noting that a new array is not a pointer to the

Arrayobj.concat (); Returns an array of copies, noting that a new array is not a pointer to the

7, the ordering of array elements

Arrayobj.reverse (); Reverse element (top to last, last to top), return array address

Arrayobj.sort (); array element Sorting, returning the arrays address

8. String of array elements

Arrayobj.join (separator); Returns a string that connects each element value of an array, separated by a separator in the middle.

toLocaleString, toString, valueof: Can be seen as a special use of join, not commonly used

9, Length property

The Length property represents the size of the array, which is the number of elements. Because the index of an array always starts with 0, the upper and lower bounds of an array are: 0 and length-1 respectively. Unlike most other languages, the length property of a JavaScript array is variable, which requires special attention. When the length property is set larger, the state of the entire array does not actually change, only the length property is larger, and when the length property is set to the previous hour, the value of the element whose index is greater than or equal to length in the original array is lost. The following is an example of changing the length property:

var arr=[12,23,5,3,25,98,76,54,56,76];

Defines an array that contains 10 digits

alert (arr.length); Displays the length of the array 10

arr.length=12; Increase the length of an array

alert (arr.length); The length of the display array has changed to 12

Alert (arr[8]); Displays the value of the 9th element, which is 56

arr.length=5; Reduces the length of the array to 5, and the elements indexed equal to or more than 5 are discarded

Alert (arr[8]); Show 9th element has changed to "undefined"

arr.length=10; Restores the array length to 10

Alert (arr[8]); Although the length is restored to 10, the 9th element cannot be retracted, displaying "undefined"

From the above code we can clearly see the nature of the length property. But the length object can be set not only explicitly, it may also be implicitly modified. You can use a variable that is not declared in JavaScript, and you can use an undefined array element (an element whose index exceeds or equal to length), at which point the value of the length property is set to the value plus 1 for the element index used. For example, the following code:

var arr=[12,23,5,3,25,98,76,54,56,76];

alert (arr.length);


alert (arr.length);

The code also first defines an array of 10 digits, which can be seen by an alert statement of 10. Then the element with index 15 is assigned to 15, or arr[15]=34, and then the length of the array is output by the alert statement, with 16. In any case, this is a surprising feature for developers who are accustomed to strongly typed programming. In fact, an array created with the new Array () has an initial length of 0, and it is an operation that does not define an element in it, which changes the length of the array.

As you can see from the above introduction, the length property is so magical that it makes it easy to increase or decrease the size of the array. Therefore, a thorough understanding of the length attribute is helpful to the flexible application in the development process.

10, prototype property

Returns a reference to the object type prototype. The prototype property is common to object.


The objectname parameter is the name of the object.

Description: Provides a set of basic functions for an object's class with the prototype property. The operation of the new instance of the object, "inherit", gives the object a prototype.

For an array object, use the following example to illustrate the purpose of the prototype property.

Adds a method to the array object that returns the maximum element value in the array. To do this, declare a function, add it to the Array.prototype, and use it.

function Array_max ()


var i, max = this[0];

for (i = 1; i < this.length; i++)


if (Max < this[i])

max = This[i];


return Max;


Array.prototype.max = Array_max;

var x = new Array (1, 2, 3, 4, 5, 6);

var y = X.max ();

After the code executes, Y saves the maximum value in the array x, or says 6

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.