Javascript has two quite powerful and popular functions among developers: split and join. These two functions can interchange both string and array types, that is, arrays can be serialized into strings, and vice versa. We can fully play these two functions. Let’s explore some interesting applications here. First, let’s introduce these two functions:
String.prototype.split(separator, limit)
The separator divides the string into an array, and the optional parameter limit defines the maximum length of the generated array.
"85@@86@@53".split('@@'); //['85','86','53'];"banana".split(); //["banana"]; //( thanks peter (-: )"president,senate,house".split(',',2); //["president", "senate"]Array.prototype.join(separator)The optional parameter separator converts the array into a string. If the separator is not provided, then the comma will be used as the parameter value (just like the toString function of the array).
["slugs","snails","puppy dog's tails"].join(' and '); //"slugs and snails and puppy dog's tails"['Giants', 4, 'Rangers', 1].join(' '); //"Giants 4 Rangers 1"[1962,1989,2002,2010].join();Here are some of the applications:
replaceAll
This simple function is not like the native replace function, it can be replaced as a global substring without using regular expressions.
String.prototype.replaceAll = function(find, replaceWith) { return this.split(find).join(replaceWith); }"the man and the plan".replaceAll('the','a'); //"a man and a plan"For small strings, it is a bit weaker than native functions replaced by a single character (here refers to two additional functions of a regular expression), but under mozilla, if the character exceeds 2 or 3 characters, this usage function runs faster than the regular expression.
Occurences
This function can get the number of substrings matched. Moreover, this kind of function is very direct and does not require regularity.
String.prototype.occurences = function(find, matchCase) { var text = this; matchCase || (find = find.toLowerCase(), text = text.toLowerCase()); return text.split(find).length-1; }document.body.innerHTML.occurences("div"); //google home page has 114document.body.innerHTML.occurences("/div"); //google home page has 57"England engages its engineers".occurrences("eng",true); //2repeatThis function is borrowed from prototype.js:
String.prototype.repeat = function(times) { return new Array(times+1).join(this); }"go ".repeat(3) + "Giants!"; //"go go go Giants!"The beauty of it lies in the use of the join function. The focus is on this separator parameter value, and then this basic array only contains some undefined value values. To illustrate this more clearly, let’s recreate the above example:
[undefined,undefined,undefined,undefined].join("go ") + "GiantsRemember that before join, each array element will be converted to a string (here is an empty string). The application of this repeat function is one of the few unfeasible applications that define arrays through array literals.
Use limit parameter
I rarely use the limit optional parameters of the split function. Here is an example using this limit:
var getDomain = function(url) { return url.split('/',3).join('/');}getDomain("http://www.aneventapart.com/2010/seattle/slides/");//"http://www.aneventapart.com"getDomain("https://addons.mozilla.org/en-US/firefox/bookmarks/");//"https://addons.mozilla.org"Modify numerical members
If we mix regulars together, join and split can easily modify array members. However, this function is not as difficult as imagined. Its main function is to remove the string specified in front of each member of the given array.
var beheadMembers = function(arr, removeStr) { var regex = RegExp("[,]?" + removeStr); return arr.join().split(regex).slice(1);}//make an array containing only the numeric portion of flight numbersbeheadMembers(["ba015","ba129","ba130"]; //["015","129","130"]Unfortunately, this function fails in IE because they mistakenly remove the first empty member from split. Now let's correct this function:
var beheadMembers = function(arr, removeStr) { var regex = RegExp("[,]?" + removeStr); var result = arr.join().split(regex); return result[0] && result || result.slice(1); //IE workaround}Why do we use this technique instead of the map function of array in Emascript 5?
["ba015","ba129","ba130"].map(function(e) { return e.replace('ba','')}); //["015","129","130"]In actual use, when feasible, I usually use the native map function (not available below IE<9). The following example is only used as a learning tool, but it is worth noting that the calling syntax of join and split is more concise and direct. Most interestingly, it is also very efficient, especially for small arrays, which is more efficient in FF and Safari. For large arrays, map functions are more suitable. (In all browsers), there will be fewer function calls to join and split functions.
//test 1 - using join/splitvar arr = [], x = 1000;while (x--) {arr.push("ba" + x);}var beheadMembers = function(arr, regex) { return arr.join().split(regex).slice(1);}var regex = RegExp("[,]?" + 'ba');var timer = +new Date, y = 1000;while(y--) {beheadMembers(arr,regex);};+new Date - timer;//FF 3.6 733ms//Ch 7 464ms//Sa 5 701ms//IE 8 1256ms//test 2 - using native map functionvar arr = [], x = 1000;while (x--) {arr.push("ba" + x);}var timer = +new Date, y = 1000;while(y--) { arr.map(function(e) { return e.replace('ba','') });}+new Date - timer;//FF 3.6 2051ms//Cr 7 732ms//Sf 5 1520ms//IE 8 (Not supported)Pattern matching
Arrays need to constantly perform pattern matching, but strings do not. Regular expressions can be used in strings, but not in arrays. The power of converting arrays into strings for pattern matching is far beyond the scope of this article. Let's take a look at a simple application of it.
Assume that the race results of the race need to be saved to the array. The purpose is to place the contestants and their recording time alternately in an array. We can use join and regular expressions to verify whether this storage pattern is correct. The following code is to find out the missed record time by looking for two consecutive names.
var results = ['sunil', '23:09', 'bob', '22:09', 'carlos', 'mary', '22:59'];var badData = results.join(',').match(/[a-zA-Z]+,[a-zA-Z]+/g);badData; //["carlos,mary"]