티스토리 뷰
String.prototype.split(separator, limit)
"85@@86@@53".split("@@"); //['85', '86', '53'];
"bannana".split(); //["banana"];
"원,투,쓰리".split(",",2); // ["원","투"]
Array.prototype.join(separator)
배열을 스트링으로 변환 합니다.
["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(); //"1962,1989,2002,2010"
replaceAll
정규 표현식을 사용하지 않고 문자열 대체 수행 예제
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"
repeat
String.prototype.repeat = function(times) {
return new Array(times+1).join(this);
}
"go ".repeat(3) + "Giants!"; //"go go go Giants!"
사용 패턴
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"
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"]
var beheadMembers = function(arr, removeStr) {
var regex = RegExp("[,]?" + removeStr);
var result = arr.join().split(regex);
return result[0] && result || result.slice(1); //IE workaround
}
패턴 매치
var results = ['sunil','23:09','bob','22:09','carlos','mary','22:59'];
var badData = results.join(',').match(/[a-zA-Z]+,[a-zA-Z]+/);
badData; //["carlos,mary"]
//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)
'웹개발 > Javascript' 카테고리의 다른 글
| Javascript RegEx Api (0) | 2010.12.14 |
|---|---|
| Javascript 키워드 몇가지 (0) | 2010.12.14 |
| 자바스크립트 여러가지 (0) | 2010.09.10 |
| 자바스크립트 With Statements (0) | 2010.09.10 |
| 자바스크립트 정규식 예제 (0) | 2010.09.10 |
댓글