javascript - 检查一个字符串在一个字符串中出现了多少次

标签 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”长度 beeing 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

关于javascript - 检查一个字符串在一个字符串中出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26056613/

相关文章:

javascript - JQuery 选择下拉列表中最接近的 tr 选择

javascript - 使用数组元素分配 “id=” 值返回 : TypeError: document. getElementById(...) 为 null

javascript - 将 StorageFile 端到端读入字符串的最简单方法?

javascript - 选中每个 <li> 的复选框时更改 <li> 的类

javascript - 如何使用变量在 for 循环中递增或递减?

JavaScript - 获取点击按钮的属性

javascript - 使用 javascript 更改后,Div 未重置其默认位置

javascript - 我如何将一个大对象映射到 es6 中的数组

javascript - 如何通过 ID 从 JSON 对象数组中删除数组元素

javascript - 多个关键帧但似乎没有运行