检查字符串在字符串中的次数

时间:2014-09-26 09:44:55

标签: javascript

我收到了这个字符串:

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

我想知道字符串“su”在longText中的次数和每个“su”的位置。

我正在尝试:

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

主文本和nr4之间的长度除以“su”lenght beeing 2之间的差异导致了一些重复,但我敢打赌,有更好的方法。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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]

答案 3 :(得分:-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++;
}