Advanced use tips for split and join functions in JavaScript _ javascript skills

Source: Internet
Author: User
This article mainly introduces the advanced use skills of the split and join functions in JavaScript. split and join are usually used to operate the conversion between arrays and strings, for more information, see Javascript. There are two very powerful and developers' favorite functions: split and join. These two functions allow the string and array types to be exchanged, that is, the array can be serialized as a string, and vice versa. We can give full play to these two functions. The following describes some interesting applications. First, we will introduce these two functions:

String. prototype. split (separator, limit)
Separator splits the string into an array. 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 an array to a string. If the separator is not provided, the comma is 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();

See the following applications:

ReplaceAll
Unlike the native replace function, this simple function can be replaced as a global substring without using a regular expression.

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 a small string, it is weaker than the native function replaced by a single character (here it refers to two additional functions of the regular expression), but in mozilla, if the character exceeds 2 or 3 characters, this function runs faster than the regular expression.

Occurences
This function can be used to obtain the number of matched substrings. In addition, such functions do not require regular expressions.

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("p"); //google home page has 114document.body.innerHTML.occurences("/p"); //google home page has 57"England engages its engineers".occurrences("eng",true); //2repeat

This function is used for reference from prototype. js:

String.prototype.repeat = function(times) {  return new Array(times+1).join(this);  }"go ".repeat(3) + "Giants!"; //"go go go Giants!"

Its beauty lies in the use of join functions. Focus is on the value of this separator parameter, and the base array only contains some undefined value values. To better illustrate this, let's recreate the above example:

[undefined,undefined,undefined,undefined].join("go ") + "Giants

Remember that each array element is converted into a string (an empty string) before join ). This repeat function is one of the few unfeasible applications that define arrays using arrays literally.

Use limit Parameters
I seldom use the limit optional parameter of the split function. The following describes an instance that uses 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 numeric Member
If we mix the regular expressions for use, join and split can easily modify the array members. However, this function is not difficult to imagine. Its main function is to remove the strings specified before each member in 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"],"ba"); //["015","129","130"]

Unfortunately, such functions do not work in IE because they mistakenly remove the first empty member from the split. Modify this function now:

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 should we use this technique instead of using the array map function in Emascript 5?

["ba015","ba129","ba130"].map(function(e) {  return e.replace('ba','')}); //["015","129","130"] 

In practical use, when feasible, I usually use native map functions (unavailable in IE <9 ). The following example serves only as a learning tool, but it is worth noting that the call Syntax of join and split is more concise and straightforward. The most interesting thing is that it is also very efficient, especially for small arrays, it is more efficient in FF and Safari. For large arrays, map functions are more suitable. (In all browsers), the join and split functions have fewer function calls.

//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
The array needs to constantly perform pattern matching, but the string does not. Regular Expressions can be used in strings, but not in arrays. Converting arrays into strings is far beyond the scope of this article. Let's take a look at a simple application.

Assume that the result of the race must be saved to the array. The goal is to put contestants and their record time in an array. We can use join and regular expressions to verify whether the storage mode is correct. The following code finds out when the record time is missed by searching 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"]

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.