Advanced use techniques of split and join functions in JavaScript _javascript skills

Source: Internet
Author: User

JavaScript has two very powerful and developer-favorite functions: Split and join two opposing functions. These functions allow string to be interchanged with array two types, that is, arrays can be serialized as strings, and vice versa. We can take these two functions to the fullest. Here's a look at some of the interesting applications, first of all, about the two functions:

String.prototype.split (separator, limit)
separator splits the string into arrays, optionally limit defines the maximum length of an array to be generated.

"85@@86@@53". Split (' @@ '); [' N ', ', ', '];
Banana ". Split (); ["Banana"]; Peter (-:)
"President,senate,house". Split (', ', 2);//["President", "Senate"]
Array.prototype.join (separator)

Optional parameter separator converts an array to a string. If separator is not provided, the comma is the value of the parameter (just like the ToString function of an array).

["Slugs", "snails", "Puppy dog ' Tails"].join (' and '); "Slugs and snails and puppy dog ' tails"
[' Giants ', 4, ' Rangers ', 1].join (');//"Giants 4 Rangers 1"
[1962,198 9,2002,2010].join ();

Here are the applications:

ReplaceAll
This simple function, unlike the native replace function, can be replaced as a global substring without the need for 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 weaker than the native function of a single character replacement (this refers to the two extra functions of the regular expression). But under Mozilla, if this character is more than 2 or 3 characters, this use function will run faster than regular expressions.

Occurences
The function can take the number of substring matches. And this function is very straightforward and does not need to be regular.

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 114
document.body.innerHTML.occurences ("/div")//google home page has
engages its engineers ". Occurrences (" eng ", true); 2
Repeat

This function is borrowed from prototype.js:

String.prototype.repeat = function (times) {return
  new Array (times+1). Join (this);

Go ". Repeat (3) +" giants! "; "Go to go giants!"

The beauty of it is the use of the join function. The focus is on the separator parameter value, and the underlying array contains only some undefined value values. To make this clearer, let's redo the example above:

[Undefined,undefined,undefined,undefined].join ("Go") + "Giants

Remember that each array element is converted to a string (here is an empty string) before the join. The application of this repeat function is one of the few infeasible applications that defines an array through the literal volume of an array.

Using the Limit parameter
I rarely use the limit optional parameter of the Split function, and here's an example 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 Members
Join,split can easily modify the array members if we mix them together. But this function is also not difficult to imagine, its main function is to remove the given array of each member before the specified string.

var beheadmembers = function (arr, removestr) {
  var regex = RegExp ("[,]?" + removestr);
  Return Arr.join (). Split (regex). Slice (1);
}

Make a array containing only the numeric portion of flight numbers
beheadmembers (["ba015", "ba129", "ba130"], "ba"); ["015", "129", "130"]

Unfortunately, this function is invalidated in IE because they mistakenly remove the first empty member from the split. Now to fix 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 Emascript the map function of array 5?

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

In practical use, when feasible, I usually use the native map function (not available under ie<9). The following example is just a learning tool, but it is worth noting that the invocation syntax for join and split is simpler and more straightforward. Most interestingly, it is also very efficient, especially for small arrays, which are more efficient in FF and Safari. For large arrays, the map function is more appropriate. The join and split functions have fewer function calls (in all browsers).

Test 1-using join/split
var 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 function< C17/>var 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 continue to perform pattern matching, but the string does not. Regular expressions can be used in strings, but not in arrays. The toughness of converting arrays into strings for pattern matching is far beyond the scope of this article. Let's look at a simple application of it.

Assume that the race race results need to be saved in the array. The goal is to place the contestants alternately in the array with their record time. We can use joins and regular expressions to verify that this storage mode is correct. The following code searches for two consecutive names to find out when the record time is missing.

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"]

Related Article

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.