2014-09-26 159 views
0

裏面我得到這個字符串:檢查字符串多少次是一個字符串

var longText="This is a superuser test, super user is is super important!"; 

我想知道字符串「蘇」有多少次是在LONGTEXT,每個「蘇」的位置。

我與努力:

var nr4 = longText.replace("su", "").length; 

而且lenght的正文和NR4的「蘇」 lenght beeing 2導致的重複次數之差除以但我敢打賭,有一個更好的辦法做到這一點。

+0

'變種的howmany = longText.split( 「ス」)length'或'VAR解析度= longtext.match(/ SU /克);' – mplungjan 2014-09-26 09:47:47

回答

2

例如

var parts=longText.split("su"); 
alert(parts.length-1); // length will be two if there is one "su" 

更多細節使用exec

FIDDLE

var re =/su/g, pos=[]; 
while ((result = re.exec(longText)) !== null) { 
    pos.push(result.index); 
} 
if (pos.length>0) alert(pos.length+" found at "+pos.join(",")); 

enter image description here

+0

確定這就是工作,所以遠,我怎麼檢查每個「蘇」的位置? – Alpha2k 2014-09-26 09:53:40

+0

var parts = longText.split(「su」)。length return nb(「su」)+ 1,bad answer .. – Hacketo 2014-09-26 10:36:55

+0

「su」.split(「su」).length = 2 – Hacketo 2014-09-26 10:51:55

0

可以這樣做:

var indexesOf = function(baseString, strToMatch){ 

    var baseStr = new String(baseString); 

    var wordLen = strToMatch.length; 
    var listSu = []; 
    // Number of strToMatch occurences 
    var nb = baseStr.split(strToMatch).length - 1; 

    for (var i = 0, len = nb; i < len; i++){ 
     var ioF = baseStr.indexOf(strToMatch); 
     baseStr = baseStr.slice(ioF + wordLen, baseStr.length); 
     if (i > 0){ 
      ioF = ioF + listSu[i-1] + wordLen; 
     } 
     listSu.push(ioF); 
    } 
    return listSu; 
} 

indexesOf("This is a superuser test, super user is is super important!","su"); 
return [10, 26, 43] 
1

使用exec。從MDN代碼修改的示例。 len包含出現次數su。 。

var myRe = /su/g; 
var str = "This is a superuser test, super user is is super important!"; 
var myArray, len = 0; 
while ((myArray = myRe.exec(str)) !== null) { 
    len++; 
    var msg = "Found " + myArray[0] + ". "; 
    msg += "Next match starts at " + myRe.lastIndex; 
    console.log(msg, len); 
} 

// "Found su. Next match starts at 12" 1 
// "Found su. Next match starts at 28" 2 
// "Found su. Next match starts at 45" 3 

DEMO

-1
var longText="This is a superuser test, super user is is super important!"; 
var count = 0; 
while(longText.indexOf("su") != -1) { // NB the indexOf() method is case sensitive! 
    longText = longText.replace("su",""); //replace first occurence of 'su' with a void string 
    count++; 
} 
+0

不建議使用破壞性方法。 – mplungjan 2014-09-26 10:47:26

相關問題