簡體   English   中英

在第n次出現的字符處剪切一個字符串

[英]Cutting a string at nth occurrence of a character

我想要做的是取一個像this.those.that這樣的字符串,並從第n個字符出現一個子字符串。 所以,從字符串的開頭到第二次出現. 將返回this.those 同樣,從第2次出現. 到字符串的結尾將返回that 對不起,如果我的問題有霧,那就不容易解釋了。 另外,請不要建議制作額外的變量,結果將是字符串而不是數組。

你可以在沒有數組的情況下完成它,但它需要更多代碼並且可讀性更低。

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

 var str = 'this.those.that', delimiter = '.', start = 1, tokens = str.split(delimiter).slice(start), result = tokens.join(delimiter); // those.that console.log(result) // To get the substring BEFORE the nth occurence var tokens2 = str.split(delimiter).slice(0, start), result2 = tokens2.join(delimiter); // this console.log(result2) 

jsFiddle

試試這個 :

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

"qwe.fs.xczv.xcv.xcv.x".replace(/([^\\.]*\\.){**nth**}/, ''); - nth是要刪除的發生量。

為了防止有人像他的評論中描述的那樣需要“this”和“that.that”,這里有一個修改過的代碼:

 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; 

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

//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這樣簡單的代碼。

如果你真的想堅持使用字符串方法,那么:

// 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM