2017-05-25 71 views
1

我有喜歡的課程代碼列表:jQuery的 - 當整數或空間中發現拆分(即拆分課程代碼)

CRS100 
CRS301 
CRS332 
...etc. 

我想拆分這些課程代碼,這樣我可以做這樣的事情:

<a data-courseProgram="CRS" data-courseCode="301">CRS301</a> 

任何幫助,將不勝感激:)

+0

都是ids 6的長度嗎? –

+0

是的,6個字符。儘管如此,也能很好地解釋課程代碼之間的空白。例如,考慮'CRS 301'。 – ymdahi

回答

3

所有你想要做的分割標識加入一半的前三個字母是一致的,剩下的就是ID,所以你可以做這樣的事情,

var s = 'CRS332'; //course ID 
var i = s.length/2; //split the string into half 
var course = s.substr(0, i); //gives you CRS 
var courseId = s.substr(i); //gives you 332 

有一個更優雅的解決方案,你也可以使用正則表達式和字符串分割成兩個部分,像

var str = 'CRS332'; 
var splitId = str.match(/.{1,3}/g); 
console.log(splitId); //outputs ['CRS', '332']; 

現在,您可以像使用分別splitId[0]splitId[1]上面的一個。


如果你有一個像CRS332和CRS 332(中間有空格),可以使用下面的代碼(我剛寫和小提琴測試,可能會錯過,你必須處理極端情況)

ID的組合
//all ids, and create a new container to push the splitted ids 
var dir = ['CRS 332', 'CRS447'], newDir = []; 

//loop all the course ids 
for(var i = 0, l = dir.length; i < l; i++) { 

    //if space exists, split it 
    if(dir[i].indexOf(' ') !== -1) { 
    //space exists in the string, do a normal split 
    newDir.push(dir[i].split(' ')); 
    } else { 
    //if no space, split it in half 
    newDir.push(dir[i].match(/.{1,3}/g)); 
    } 
} 

console.log(newDir); 
+0

另外,你的問題還不清楚,如果你說你的課程編號也可以有空格,只要放入並且如果條件檢查字符串的長度,如果它超過6,這很簡單,你可以使用''YOUR STRING'.split('')'它會爲你分割 –

+0

感謝您的詳細解答,隊友! – ymdahi