SoFunction
Updated on 2025-02-28

Interesting ways to operate JavaScript string String and Array

Strings and arrays are very commonly used types during programming, so programming languages ​​will use String and Array as basic types and provide many strings and array methods to simplify the operation of strings. JavaScript also provides String type and Array type, and there are many basic String methods and Array methods to facilitate merging, searching, replacing, intercepting strings.

As a scripting language, JavaScript also provides a mechanism for dynamic parsing and operation, and this feature makes some interesting methods of using Array in combination when operating String. These methods may be a bit strange, but sometimes they perform better in terms of efficiency, readability, and reusability.

Repeat string
Often, if we want to print out the string multiple times (for example, if we want a split line), we need to repeat a string multiple times. Unfortunately, JavaScript does not provide a method like repeat. Of course we can use loops to splice it out, but we can use the join method of Array in JavaScript to implement repeat
Copy the codeThe code is as follows:

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

By using n gaps generated by n+1 Array elements and then splicing them with the target string, we can get the function of string duplication.
Extend String's prototype to apply methods to all strings
JavaScript object inheritance and method search is based on a prototype chain. All strings used can be said to be objects inherited from String. 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 codeThe code is as follows:

= function(n) {
var arr = new Array(n+1);
return (this);
};
('-'.repeat(21));
//output:
//---------------------

Then, call the repeat method directly through the string to get the same result as above.
This allows us to expand string methods and concisely operate strings, but this will "pollute" JavaScript's String. When the code is transferred to another file but the file does not have this expansion, it may cause the method to not be found; in addition, calling the prototype extension method is slightly "slower" than calling the method directly, because JavaScript will first try to find the method in the string object's own method, and then find the String's prototype method; and in the future, the method we expanded (such as repeat) may become a standard method, and then use this code will overwrite the standard method and obtain inconsistent results.

However, ignoring these considerations, expanding JavaScript standard prototypes will still bring a lot of traversal to programming.

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

JavaScript also supports the use of plus sign (+) for string splicing, so there will be efficiency problems. However, JavaScript does not provide a class like StringBuilder.

In fact, when using StringBuilder in Java and C#, most of us also use the append method, and rarely use insert. Fortunately, JavaScript's Array automatically grows without limiting its size, so we can use Array to make StringBuilder, and finally join the empty string to splice out the target string.
Copy the codeThe code is as follows:

var sb = [];
for(var i = 0; i <=21; i++) {
(i);
}
((''));
//output:
//0123456789101112131415161718192021

Whether to use Array for StringBuilder or to splice strings directly? There are many testcases on jsPerf that compare the efficiency of the two, but due to the initial value, environment, string length and other reasons, the results are different. In fact, the string content is not very large, or multiple plus signs (+) can be used to combine them together, then string splicing is still possible; if the same string variable is appended in different parts of the code, it may be better to use Array and join.

Replace substrings of strings with split instead of strings
In string operations, it is common to find out whether a substring exists from the string, then intercept the string, or replace the substring with other strings.

For example, give a file name, and hope to obtain the basic name and suffix name according to the dot (.). Let’s first look at these operations implemented using the standard String method:
Copy the codeThe code is as follows:

function getBaseName(str) {
var pos = ('.');
if(pos < 0)return str;
return (0, pos);
}
function getExtension(str) {
var pos = ('.');
if(pos < 0)return '';
return (pos+1);
}
var fileName = 'hello_world.js';
(getBaseName(fileName));
('<br />');
(getExtension(fileName));
//output:
//hello_world
//js

(In addition to substr and substring, JavaScript and slice can be used to obtain substrings of strings, but it is precisely because of too many choices that often make me panic in choosing, and the position should be +1, and how to deal with negative numbers is also worrying.)

I saw before that you can turn an array into a string through join, or you can use the String split method to turn a string into an array. For the above problem of getting file names and extensions, we can split the file names into parts of the array based on "." Then if the obtained number is greater than 1 (the suffix exists), the last element of the obtained number is the file extension:
Copy the codeThe code is as follows:

function getBaseName(str) {
var segs = ('.');
if( > 1) ();
return ('.');
}
function getExtension(str) {
var segs = ('.');
if( <= 1)return '';
return ();
}

Considering that the file name may contain multiple ".", we still need to use "." to join each part except the last part.
When you see that you can split the string first and then join, you can think that we can think that different strings can be passed into the parameters of these two methods, which can play the role of substring replacement instead of String's replace method, and it is also a global replacement.
For example, I hope to replace all underscores (_) with horizontal bars (-):
Copy the codeThe code is as follows:

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

Compared with String's replace method, the point of this method is that global replacement can be implemented; and if replace can be replaced globally, you need to pass in a regular expression object (RegExp) instead of a string as the first parameter.

replace can accept RegExp and Function as parameters
Many people know that String's replace method is used to replace string substrings, or they may know that it can accept regular expressions as the first parameter, and how to replace all places where it occurs must be used with RegExp and include global tags.
For example, in the previous replacement operation, using replace should be:
Copy the codeThe code is as follows:

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

For example, the most commonly used trim method, although JavaScript does not provide us, we can implement it quickly by ourselves:
Copy the codeThe code is as follows:

= function() {
return (/^\s+|\s+$/g, '');
};

We know that a very powerful function of regular expressions is backward reference (Back Reference). In fact, JavaScript replace not only makes backward references in the first parameter, but also makes backward references on the replacement string. However, in many places, backslash (\) plus numbers may be used as marks, while JavaScript uses US ($) plus numbers as marks.
Copy the codeThe code is as follows:

var friends = 'friends of Ider, friend of Angie';
var result = (/(friends?) of (\w+)/g, "$2's $1");
(result);
//output:
//Ider's friends, Angie's friend

By backward references inside the replacement string, we quickly turned "friends of so-so" into "so-so-so-friends". What if it is 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, and then each represents the match referenced backwards, and the return value of the function is the string as a replacement. Therefore, many use functions are expressed in $0, $1, $2. Let’s take a look at an example:
Copy the codeThe code is as follows:

var friends ="friends of mine, friend of her and friends of his";
var result = (/(friends?) of (\w+)/g,
function($0, $1, $2) {
if($2 == 'mine') $2 = 'my';
return $2 + ' ' + $1;
});
(result);
//output:
//my friends, her friend and his friends

Through the callback function, many very responsible string matching can be achieved. As for efficiency, I won’t consider it for now.