您好,欢迎访问一九零五行业门户网

JavaScript中split与join函数的进阶使用技巧_javascript技巧

javascript拥有两个相当强大而且受开发者喜爱的函数:split 与join 俩对立的函数。这俩函数能让string与array两种类型互换,也就是数组能被序列化为字符串,反之亦然。我们能把这俩函数发挥得淋漓尽致。下面就来探索里面的一些有趣的应用, 首先介绍一下这两个函数:
string.prototype.split(separator, limit)
separator把字符串分割为数组,可选参数limit定义了生成数组的最大length。
85@@86@@53.split('@@'); //['85','86','53'];banana.split(); //[banana]; //( thanks peter (-: )president,senate,house.split(',',2); //[president, senate]array.prototype.join(separator)
可选参数separator把数组转换为一个字符串。如果不提供separator,那么就会把逗号做为这个参数值(就跟数组的tostring函数一样)。
[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();
下面来看这些应用:
replaceall
这个简单的函数不像原生的replace函数,它能作为一个全局的子字符串替换而不需要使用正则表达式。
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
对于小的字符串,它比单个字符替换的原生函数性能要弱一些(这里指的是正则表达式的两个额外的函数),但是在mozilla下,如果这个字符超过2个或3个字符话,这种使用函数要比正则表达式运行得更快。
occurences
该函数能取到子字符串匹配的个数。而且这种函数很直接不需要正则。
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 57england engages its engineers.occurrences(eng,true); //2repeat
该函数是从prototype.js 借鉴而来:
string.prototype.repeat = function(times) { return new array(times+1).join(this); }go .repeat(3) + giants!; //go go go giants!
它的美妙之处就在于join函数的使用。焦点就在这个separator参数值,然后这个基础数组仅仅包含了一些未定义的value值。为了更清楚的说明这点,我们来重造一下上面的实例:
[undefined,undefined,undefined,undefined].join(go ) + giants
记住在join之前每个数组元素都会转换为一个字符串(这里就是一个空字符串)。这个repeat函数的应用是通过数组字面量定义数组的为数不多的不可行的应用。
使用limit参数
我很少使用split函数的limit可选参数,下面介绍一个使用这个limit的实例:
var getdomain = function(url) { return url.split('/',3).join('/');}getdomain(http://www.aneventapart.com/2010/seattle/slides/);//http://www.aneventapart.comgetdomain(https://addons.mozilla.org/en-us/firefox/bookmarks/);//https://addons.mozilla.org
修改数值成员
如果我们将正则混合起来使用,join,split就能很容易的修改数组成员了。但是这个函数也没有想象的难,它的主要功能是去掉给定数组的每个member前面指定的字符串。
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]
不幸的是,这种函数在ie中失效,因为他们从split中错误的去掉了第一个空成员。现在来修正这种函数:
var beheadmembers = function(arr, removestr) { var regex = regexp([,]? + removestr); var result = arr.join().split(regex); return result[0] && result || result.slice(1); //ie workaround}
我们为什么要用这个技巧而不用emascript 5 中array 的map函数呢?
[ba015,ba129,ba130].map(function(e) { return e.replace('ba','')}); //[015,129,130]
在实际的运用中,在可行的时候,我通常使用原生的map函数(在ie<9 以下不可用)。下面的例子仅仅作为学习的工具,但是值得注意的是,join与split的调用语法更简洁更直接一些。最有趣的是,它也非常高效,尤其是对于很小的数组,在ff与safari中它表现为更为高效。对于大数组来说,map函数就更合适一些。(在所有的浏览器中),join与split函数的函数调用会少一些。
//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)
模式匹配
数组需要不断的去执行模式匹配,但是字符串不会。正则表达式能在字符串中运用,但是在数组中不会。把数组转为字符串用于模式匹配的强悍之处远远超越这篇文章讲述的范围。让我们来看看它的一个简单应用。
假设竞走的比赛结果需要保存到数组中。目的就是将竞赛者与他们的记录时间交替的放在数组中。我们可以用join与正则表达式来验证这种存储模式是否正确。下面的代码就是通过查找两个连续的名字来找出记录时间被漏掉的情况。
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]
其它类似信息

推荐信息