我得到了这个字符串:
var longText="This is a superuser test, super user is is super important!";
我想知道字符串“su”在longText中出现了多少次以及每个“su”的位置。
我正在尝试:
var nr4 = longText.replace("su", "").length;
正文和 nr4 之间的长度差异除以“su”长度 beeing 2 会导致多次重复,但我打赌有更好的方法。
最佳答案
例如
var parts=longText.split("su");
alert(parts.length-1); // length will be two if there is one "su"
使用 exec 获取更多详细信息
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(","));
<小时/>
关于javascript - 检查一个字符串在一个字符串中出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26056613/