2011-03-31 96 views
39

我想要做的是取一個字符串,如this.those.that,並從第n次出現字符時得到一個子字符串。因此,從字符串開始到.的第二次出現將返回this.those。同樣,從第二次出現.到字符串的末尾將返回that。對不起,如果我的問題很模糊,解釋起來並不容易。另外,請不要建議做額外的變量,結果將在字符串中而不是數組。在第n次出現字符時剪切字符串

+1

任何異議分裂成一個數組,然後連接數組的切片?它使用對字符串進行操作或生成字符串的函數。 – tvanfosson 2011-03-31 02:26:31

+1

看來你已經知道了答案;在分隔符上分割字符串,然後用這些部分重新構建一個新的字符串似乎是最好的選擇。爲什麼限制自己不使用數組? – Tejs 2011-03-31 02:27:05

+1

一個字符串是一個數組。 – Incognito 2011-03-31 02:32:02

回答

67

你可以在沒有數組的情況下做到這一點,但它需要更多的代碼並且可讀性較差。

通常,您只想使用盡可能多的代碼來完成工作,這也增加了可讀性。如果您發現此任務正在成爲性能問題(基準測試),則可以選擇然後,您可以決定開始重構性能。

var str = 'this.those.that', 
    delimiter = '.', 
    start = 1, 
    tokens = str.split(delimiter).slice(start), 
    result = tokens.join(delimiter); // those.that 

jsFiddle

+1

我認爲結果應該是「this.those」和「that」? – tvanfosson 2011-03-31 02:45:16

+0

@tvanfosson也許我誤解了這個問題,但它被接受:) – alex 2011-03-31 03:10:24

+5

哇,這個答案是驚人的,謝謝亞歷克斯! – iamserious 2011-09-14 17:05:02

3

我困惑,爲什麼你想用字符串函數做的事情純粹,但我想你可以做類似如下:

//str  - the string 
//c   - the character or string to search for 
//n   - which occurrence 
//fromStart - if true, go from beginning to the occurrence; else go from the occurrence to the end of the string 
var cut = function (str, c, n, fromStart) { 
    var strCopy = str.slice(); //make a copy of the string 
    var index; 
    while (n > 1) { 
     index = strCopy.indexOf(c) 
     strCopy = strCopy.substring(0, index) 
     n--; 
    } 

    if (fromStart) { 
     return str.substring(0, index); 
    } else { 
     return str.substring(index+1, str.length); 
    } 
} 

不過,我強烈主張像Alex的簡單得多的代碼。

+0

+ +1努力:) – 2012-10-30 14:52:29

1

如果你真的要堅持字符串的方法,那麼:

// Return a substring of s upto but not including 
// the nth occurence of c 
function getNth(s, c, n) { 
    var idx; 
    var i = 0; 
    var newS = ''; 
    do { 
    idx = s.indexOf(c); 
    newS += s.substring(0, idx); 
    s = s.substring(idx+1); 
    } while (++i < n && (newS += c)) 
    return newS; 
} 
3

試試這個:

"qwe.fs.xczv.xcv.xcv.x".replace(/([^\.]*\.){3}/, ''); 
"xcv.xcv.x" 

"qwe.fs.xczv.xcv.xcv.x".replace(/([^\.]*\.){**nth**}/, ''); - 這裏是第n次是發生的去除量。

+0

這個比接受的答案要好,有時分隔符可能是正則表達式(例如\ s +)。情況下,接受的答案將不起作用他會的。 – killua8p 2016-01-14 05:21:40

+0

@ killua8p奇怪的推理。如果*有時分隔符可能是一個正則表達式*你可以這樣設計它。如果是分割字符串,你不應該總是喜歡正則表達式,因爲*你可能需要它*。 YAGNI。 – alex 2016-04-28 09:11:44

+0

這個快了大約4倍。 – jazzgil 2017-07-25 05:34:20

2

萬一有人需要兩個「this」和「those.that」的亞歷克斯在他comment描述的方式,這裏是一個修改後的代碼:

var str = 'this.those.that', 
 
    delimiter = '.', 
 
    start = 1, 
 
    tokens = str.split(delimiter), 
 
     result = [tokens.slice(0, start), tokens.slice(start)].map(function(item) { 
 
    return item.join(delimiter); 
 
    }); // [ 'this', 'those.that' ] 
 

 
document.body.innerHTML = result;

相關問題