2014-09-26 137 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

相关问题