Interesting methods for String and Array Operations on JavaScript strings

Source: Internet
Author: User
Tags string methods javascript array

Strings and arrays are commonly used in programming. Therefore, the programming language uses String and Array as the basic types, it also provides many string and array methods to simplify string operations. JavaScript also provides the String and Array types, and there are many basic String methods and Array methods to conveniently merge, search, replace, and intercept strings.

JavaScript, as a scripting language, provides a mechanism for dynamic parsing and running. This feature also gives you some interesting methods to use Array in combination during String operations. These methods may be a bit odd, but sometimes they do better in terms of efficiency, readability, and reusability.

Duplicate string
We often want to print the string multiple times (for example, to split the line), we need to repeat the string multiple times. Unfortunately, JavaScript does not provide methods like repeat. Of course we can concatenate them using loops, but we can use the join method of Array in JavaScript to implement repeat.Copy codeThe Code is as follows: function repeat (str, n ){
Var arr = new Array (n + 1 );
Return arr. join (str );
}
// Output:
//-------

Using n + 1 Array elements to generate n gaps and concatenate the target string, we can obtain the string repetition function.
Extend the prototype of String to apply the method to all strings.
JavaScript Object Inheritance and Method Searching are based on prototype chain. All strings used can be said to be objects inherited from String, we can add methods or attributes for the prototype of the String object, so that this method can be applied to all the objects we use. For example, the repeat method above can be changed:Copy codeThe Code is as follows: String. prototype. repeat = function (n ){
Var arr = new Array (n + 1 );
Return arr. join (this );
};
Document. write ('-'. repeat (21 ));
// Output:
//---------------------

Then, you can call the repeat method directly through the string to get the same result as the above one.
This allows us to expand the String method, which is simple for String operations, but this will "pollute" the String of JavaScript, when the code is transferred to another file but the file does not get this extension, this method may not be found. In addition, calling the prototype extension method is a little slower than calling the method directly, because JavaScript will first try to find it in the method of the String object itself, and then find the prototype method of the String; in addition, in the future, the extended method (such as repeat) may become a standard method. Using this code will overwrite the standard method and get inconsistent results.

However, ignoring these considerations, extending the prototype of the JavaScript standard type still brings a lot of traversal to programming.

Use Array as StringBuilder
In many advanced languages, plus signs (+) are given more meaning in string operations: as operators for String concatenation. However, in Java and C #, we also know how to concatenate strings frequently. Using the plus sign (+) will cause efficiency problems, therefore, StringBuilder is recommended in this case.

JavaScript also supports the use of the plus sign (+) for String concatenation, so there will be efficiency problems. However, JavaScript does not provide classes such as StringBuilder.

In fact, when using StringBuilder in Java and C #, most of us also use the append method, but seldom use insert. Fortunately, the JavaScript Array automatically increases with unlimited size, so we can use Array for StringBuilder, and then join an empty string to splice the target string.Copy codeThe Code is as follows: var sb = [];
For (var I = 0; I <= 21; I ++ ){
Sb. push (I );
}
Document. write (sb. join (''));
// Output:
// 0123456789101112131415161718192021

Whether to use Array for StringBuilder or directly concatenate strings, there are many testcases on jsPerf to compare the efficiency of the two, but the results are different because of the initial value, environment, string length, and other reasons. In fact, the string content is not very large, or you can use multiple plus signs (+) to combine them, then String concatenation is still possible; if you append the same string variable in different places of the Code, it may be better to use Array in combination with join.

Use split to replace string substring search and replacement
In a string operation, it is often used to find out whether a substring exists from the string, capture the substring, or replace the substring with other strings.

For example, to give a file name, you want to obtain the basic name and suffix name based on the dot. Let's take a look at the operations implemented using the standard String method:Copy codeThe Code is as follows: function getBaseName (str ){
Var pos = str. lastIndexOf ('.');
If (pos <0) return str;
Return str. substring (0, pos );
}
Function getExtension (str ){
Var pos = str. lastIndexOf ('.');
If (pos <0) return '';
Return str. substr (pos + 1 );
}
Var fileName = 'Hello _ world. js ';
Document. write (getBaseName (fileName ));
Document. write ('<br/> ');
Document. write (getExtension (fileName ));
// Output:
// Hello_world
// Js

(In addition to substr and substring, JavaScript and slice can be used to obtain string substrings, but it is precisely because there are too many choices that often make me panic in selection, there is also a location where it should not be + 1. I am worried about how to deal with negative numbers .)

Previously we can see that the array can be converted into a String through join, or the String can be converted into an array using the String split method. For the problem of getting the file name and extension above, we can refer to ". split the file name into various parts of the array. If the obtained number is greater than 1 (the suffix exists), the last element of the obtained number is the file extension:Copy codeThe Code is as follows: function getBaseName (str ){
Var segs = str. split ('.');
If (segs. length> 1) segs. pop ();
Return segs. join ('.');
}
Function getExtension (str ){
Var segs = str. split ('.');
If (segs. length <= 1) return '';
Return segs. pop ();
}

Considering that the file name may contain multiple ".", we still need to use "." To join all parts except the last part.
We can see that we can split the strings and then join them. We can think that we can input different strings for the parameters of these two methods, in this way, the replace method of String is used to replace the substring, and it is still replaced globally.
For example, you want to replace all underscores (_) with hyphens (-):Copy codeThe Code is as follows: var str = 'Hello _ from_ider_to_world '. split (' _ '). join ('-');
Document. write (str );
// Output:
// Hello-from-ider-to-world

Compared with the String replace method, this method can implement global replacement. To enable global replacement for replace, You need to input a regular expression object (RegExp) it cannot be a string as the first parameter.

Replace can accept RegExp and Function as parameters.
Many people know that the String replace method is used to replace String substrings. It may also know that it can accept regular expressions as the first parameter and how to replace all occurrences of strings, you must use RegExp and contain the global mark.
For example, in the previous replace operation, replace should be:Copy codeThe Code is as follows: var str = 'Hello _ from_ider_to_world '. replace (/_/g ,'-');
Document. write (str );

Another example is the commonly used trim method. Although JavaScript is not provided, we can implement it quickly:Copy codeThe Code is as follows: String. prototype. trim = function (){
Return this. replace (/^ \ s + | \ s + $/g ,'');
};

We know that a very powerful function of regular expressions is Back Reference. In fact, the replace of JavaScript not only performs Back Reference in the first parameter, but also replaces the string, you can also perform backward reference, but in many cases, the backslash (\) and numbers may be used as the marker, while JavaScript uses a dollar ($) and a number as the marker.Copy codeThe Code is as follows: var friends = 'friends of Ider, friend of angie ';
Var result = friends. replace (/(friends ?) Of (\ w +)/g, "$2's $1 ");
Document. write (result );
// Output:
// Ider's friends, Angie's friend

By making backward references in the replacement string, we quickly changed "Friends of WHO who" into "Who who are friends ". What if it is more complex? It doesn't matter. replace can also accept the Function as a parameter as a callback Function. The first parameter of the Function is the entire matching string, and then each parameter represents a backward reference matching, the Return Value of the function is the replacement string. For this reason, function parameters are represented by $0, $1, and $2. Let's look at an example:Copy codeThe Code is as follows: var friends = "friends of mine, friend of her and friends of his ";
Var result = friends. replace (/(friends ?) Of (\ w +)/g,
Function ($0, $1, $2 ){
If ($2 = 'Mine ') $2 = 'my ';
Return $2 + ''+ $1;
});
Document. write (result );
// Output:
// My friends, her friend and his friends

Through the callback function, we can implement many very responsible string matching. As for efficiency, we will not consider it first.

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.