Alpha2k
Alpha2k

Reputation: 2241

Check how many times a string is inside a string

I got this string:

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

I want to know how many times the string "su" is in longText and the position of each "su".

I was trying with:

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

And the difference of lenght between the main text and the nr4 divided by "su" lenght beeing 2 is resulting a number of repetitions but i bet there is a better way of doing it.

Upvotes: 0

Views: 48

Answers (4)

mplungjan
mplungjan

Reputation: 177940

For example

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

More details using 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

Upvotes: 2

Hacketo
Hacketo

Reputation: 4997

Could do :

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]

Upvotes: 0

Marco Mercuri
Marco Mercuri

Reputation: 1127

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

Upvotes: -1

Andy
Andy

Reputation: 63524

Use exec. Example amended from the MDN code. len contains the number of times su appears.

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

Upvotes: 1

Related Questions