Home >Web Front-end >JS Tutorial >Interesting ways to manipulate String and Array in JavaScript_javascript tips

Interesting ways to manipulate String and Array in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:46:131039browse

Strings and arrays are very commonly used types in programming, so programming languages ​​will use String and Array as basic types and provide many string and array methods to simplify string operations. JavaScript also provides String types and Array types, and there are many basic String methods and Array methods to easily merge, search, replace, intercept, etc. strings.

As a scripting language, JavaScript also provides a dynamic parsing and running mechanism, and this feature allows some interesting methods to be combined with Array when operating String. These methods may be a bit biased and strange, but sometimes they perform better in terms of efficiency, readability, and reusability.

Repeat a string
Often when we want to print a string multiple times (for example, if we want a dividing line), we need to repeat a string multiple times, which is a pity. JavaScript does not provide methods like repeat. Of course we can use loops to splice them together, but we can use the join method of Array in JavaScript to implement repeat

Copy code The code is as follows :

function repeat(str, n) {
var arr = new Array(n 1);
return arr.join(str);
}
/ /output:
//-------

Using n gaps generated by n 1 Array elements, and then concatenating them with the target string, we can get the string Duplicate functionality.
Extend the String prototype to apply the method to all strings
JavaScript’s object inheritance and method search are based on the prototype chain, and all used strings can be said to be inherited For String objects, we can add methods or attributes to the prototype of the String object, so that the method can be applied to all objects we use. For example, the repeat method above can be changed to:
Copy the code The 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, By calling the repeat method directly through the string, you can get the same result as above.
This allows us to expand the string method and simplify string operations, but this will "pollute" the JavaScript String. When the code is transferred to other files, this extension is not obtained in that file. , it may cause the method not to be found; in addition, calling the prototype extension method is slightly "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 of String Method; Furthermore, maybe in the future our expanded methods (such as repeat) will become standard methods, and then using this code will overwrite the standard methods and obtain inconsistent results.

But regardless of these considerations, extending the JavaScript standard type prototype will still bring a lot of traversal to programming.

Using Array as StringBuilder
In many high-level languages, the plus sign () has been given more meaning in string operations: as an operator for string concatenation . However, in Java and C#, we also know how to perform string splicing operations frequently. Using the plus sign () will cause efficiency problems, so in this case it is recommended to use StringBuilder.

JavaScript also supports the use of the plus sign ( ) for string concatenation, but there will also be efficiency issues. But JavaScript does not provide a class like StringBuilder.

In fact, when using StringBuilder in Java and C#, most of us use the append method and rarely use insert. Fortunately, JavaScript's Array automatically grows without limit on size, so we can use Array as StringBuilder, and finally join the empty string to splice the target string.
Copy code The 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 direct string splicing? There have been many testcases on jsPerf to compare the efficiency of the two. However, the results are different due to reasons such as initial value, environment, string length, etc. In fact, the content of the string is not very large, or multiple plus signs ( ) can be used to combine them, so string splicing is still possible; if the same string variable is appended in different places in the code, it may be more efficient to use Array with join. good.

Use split to replace substring search and replace of string
In string operations, it is very common to want to find whether a substring from a string is exists, and then intercept the string, or replace the substring with another string.

For example, if you give a file name, you want to get the base name and suffix separated by dot (.). Let’s first take a look at these operations implemented using standard String methods:
Copy the code The 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('
');
document.write(getExtension(fileName));
//output:
//hello_world
//js

(In addition to substr and substring, JavaScript also has slice Both can be used to obtain substrings of strings, but it is precisely because there are too many choices that I often panic when choosing. I also worry about whether the position should be 1, and how to deal with negative numbers)

I saw before that you can turn an array into a string through join, or you can use String's split method to turn a string into an array. For the above problem of getting the file name and extension, we can split the file name into various parts of the array according to ".", then if the number obtained is greater than 1 (the suffix name exists), then the last element of the number obtained is the file's Extension:
Copy code The 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.
Seeing that you can split a string first and then join it, you can think of it. We can think of passing in different strings for the parameters of these two methods, which can replace the replace method of String for substring replacement. Function, and it is a global replacement.
For example, if you want to replace all underscores (_) with dashes (-):
Copy the code The code is as follows:

var str = 'hello_from_ider_to_world'.split('_').join('-');
document.write(str);
//Output:
/ / hello-from-ider-to-world

Compared with String's replace method, the advantage of this method is that it can achieve global replacement; if you want replace to be able to replace globally, you need to pass in Regular expression object (RegExp) rather than a string as the first parameter.

replace accepts RegExp and Function as parameters
Many people know that the replace method of String is used to replace string substrings, and they may also know that it can accept regular expressions as The first parameter, and if you want to replace all occurrences, you must use RegExp and include the global tag.
For example, the previous replacement operation should be:
Copy the code The code is as follows:

var str = 'hello_from_ider_to_world'.replace(/_/g, '-');
document.write(str);

Another example is the very commonly used trim method, although JavaScript does not provide a quick implementation that we can implement ourselves:
Copy the code The 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, JavaScript's replace not only makes a backward reference in the first parameter, but also can make a backward reference in the replacement string. Post-quote, but in many places, backslash () plus numbers may be used as markings, while JavaScript uses dollars ($) plus numbers as markings.
Copy code The 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 turned "friends of so and so" into "friends of so and so". What if it’s more complicated? It doesn't matter, replace can also accept Function as a parameter as a callback function. The first parameter of the function is the string in the entire match. Each subsequent parameter represents a backward reference to the match, and the return value of the function is used as the replacement. String. Therefore, in many uses, function parameters are represented by $0, $1, $2. Let’s look at an example:
Copy code The 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

A lot of very responsible string matching can be achieved through callback functions. As for efficiency, let’s not consider it for now.
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