JavaScript中split與join函數的進階提示,splitjoin

來源:互聯網
上載者:User

JavaScript中split與join函數的進階提示,splitjoin

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函數,它能作為一個全域的子字串替換而不需要使用Regex。

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"

對於小的字串,它比單個字元替換的原生函數效能要弱一些(這裡指的是Regex的兩個額外的函數),但是在mozilla下,如果這個字元超過2個或3個字元話,這種使用函數要比Regex運行得更快。

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 57"England 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之前每個數組元素都會轉換為一個字串(這裡就是一個Null 字元串)。這個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.com"getDomain("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)

模式比對
數組需要不斷的去執行模式比對,但是字串不會。Regex能在字串中運用,但是在數組中不會。把數組轉為字串用於模式比對的強悍之處遠遠超越這篇文章講述的範圍。讓我們來看看它的一個簡單應用。

假設競走的比賽結果需要儲存到數組中。目的就是將競賽者與他們的記錄時間交替的放在數組中。我們可以用join與Regex來驗證這種儲存模式是否正確。下面的代碼就是通過尋找兩個連續的名字來找出記錄時間被漏掉的情況。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.