這篇文章主要介紹了JavaScript中split與join函數(shù)的進階使用技巧,split和join通常被用來操作數(shù)組和字符串之間的轉換,需要的朋友可以參考下
Javascript擁有兩個相當強大而且受開發(fā)者喜愛的函數(shù):split 與join 倆對立的函數(shù)。這倆函數(shù)能讓string與array兩種類型互換,也就是數(shù)組能被序列化為字符串,反之亦然。我們能把這倆函數(shù)發(fā)揮得淋漓盡致。下面就來探索里面的一些有趣的應用, 首先介紹一下這兩個函數(shù):
String.prototype.split(separator, limit)
separator把字符串分割為數(shù)組,可選參數(shù)limit定義了生成數(shù)組的最大length。
"85@@86@@53".split('@@'); //['85','86','53'];
"banana".split(); //["banana"]; //( thanks peter (-: )
"president,senate,house".split(',',2); //["president", "senate"]
Array.prototype.join(separator)
可選參數(shù)separator把數(shù)組轉換為一個字符串。如果不提供separator,那么就會把逗號做為這個參數(shù)值(就跟數(shù)組的toString函數(shù)一樣)。
["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
這個簡單的函數(shù)不像原生的replace函數(shù),它能作為一個全局的子字符串替換而不需要使用正則表達式。
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"
對于小的字符串,它比單個字符替換的原生函數(shù)性能要弱一些(這里指的是正則表達式的兩個額外的函數(shù)),但是在mozilla下,如果這個字符超過2個或3個字符話,這種使用函數(shù)要比正則表達式運行得更快。
occurences
該函數(shù)能取到子字符串匹配的個數(shù)。而且這種函數(shù)很直接不需要正則。
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 57
"England engages its engineers".occurrences("eng",true); //2
repeat
該函數(shù)是從prototype.js 借鑒而來:
String.prototype.repeat = function(times) {
return new Array(times+1).join(this);
}
"go ".repeat(3) + "Giants!"; //"go go go Giants!"
它的美妙之處就在于join函數(shù)的使用。焦點就在這個separator參數(shù)值,然后這個基礎數(shù)組僅僅包含了一些未定義的value值。為了更清楚的說明這點,我們來重造一下上面的實例:
[undefined,undefined,undefined,undefined].join("go ") + "Giants
記住在join之前每個數(shù)組元素都會轉換為一個字符串(這里就是一個空字符串)。這個repeat函數(shù)的應用是通過數(shù)組字面量定義數(shù)組的為數(shù)不多的不可行的應用。
使用limit參數(shù)
我很少使用split函數(shù)的limit可選參數(shù),下面介紹一個使用這個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"
修改數(shù)值成員
如果我們將正則混合起來使用,join,split就能很容易的修改數(shù)組成員了。但是這個函數(shù)也沒有想象的難,它的主要功能是去掉給定數(shù)組的每個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 numbers
beheadMembers(["ba015","ba129","ba130"],"ba"); //["015","129","130"]
不幸的是,這種函數(shù)在IE中失效,因為他們從split中錯誤的去掉了第一個空成員?,F(xiàn)在來修正這種函數(shù):
var beheadMembers = function(arr, removeStr) {
var regex = RegExp("[,]?" + removeStr);
var result = arr.join().split(regex);
return result[0] && result || result.slice(1); //IE workaround
}
我們?yōu)槭裁匆眠@個技巧而不用Emascript 5 中array 的map函數(shù)呢?
["ba015","ba129","ba130"].map(function(e) {
return e.replace('ba','')
}); //["015","129","130"]
在實際的運用中,在可行的時候,我通常使用原生的map函數(shù)(在IE<9 以下不可用)。下面的例子僅僅作為學習的工具,但是值得注意的是,join與split的調用語法更簡潔更直接一些。最有趣的是,它也非常高效,尤其是對于很小的數(shù)組,在FF與Safari中它表現(xiàn)為更為高效。對于大數(shù)組來說,map函數(shù)就更合適一些。(在所有的瀏覽器中),join與split函數(shù)的函數(shù)調用會少一些。
//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
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)
模式匹配
數(shù)組需要不斷的去執(zhí)行模式匹配,但是字符串不會。正則表達式能在字符串中運用,但是在數(shù)組中不會。把數(shù)組轉為字符串用于模式匹配的強悍之處遠遠超越這篇文章講述的范圍。讓我們來看看它的一個簡單應用。
假設競走的比賽結果需要保存到數(shù)組中。目的就是將競賽者與他們的記錄時間交替的放在數(shù)組中。我們可以用join與正則表達式來驗證這種存儲模式是否正確。下面的代碼就是通過查找兩個連續(xù)的名字來找出記錄時間被漏掉的情況。
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"]