Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在indexOf中的位置添加文本_Javascript_Jquery_Wordpress - Fatal编程技术网

Javascript 在indexOf中的位置添加文本

Javascript 在indexOf中的位置添加文本,javascript,jquery,wordpress,Javascript,Jquery,Wordpress,我正在根据字符串出现的次数将文本插入某些wordpress帖子的底部。我已经使用append将文本添加到底部,但是我想使用indexOf在特定位置插入 原文如下: if ($('body').hasClass("single-post")){ var count = 0; var cSearch = $('body').text(); var words = cSearch.indexOf('Words To Find')

我正在根据字符串出现的次数将文本插入某些wordpress帖子的底部。我已经使用append将文本添加到底部,但是我想使用indexOf在特定位置插入

原文如下:

 if ($('body').hasClass("single-post")){
        var count = 0;
        var cSearch = $('body').text();
        var words = cSearch.indexOf('Words To Find')
            while (words !== -1){
            count++;
            words = cSearch.indexOf('Words To Find', words + 1);
            }
        if( count >= 2){
        $('.entry-content').append('<br><br>Sample Text');
        }
    }
如何将“示例文本”拼接到使用insertLocation指定的位置

我发现了一些关于使用polyfil进行.拼接的方法,但我不确定它是否适用于此。使用它,例如:

$(cSearch).splice( insertLocation, -1 ).text( "Sample Text" );

有人能建议一种方法吗?谢谢

尝试创建表示总匹配的变量,
indexOf()
match加上匹配的文本
.length
,使用
.slice()
在第二次匹配之前插入原始文本,插入新文本,然后插入原始文本的其余部分

var text=$(“div”).text(),
match=“要查找的单词”,
txt=“示例文本”,
匹配项=0,
n=0,
//`max`:插入`txt'之前的`matches`总数`
max=2;
while(匹配<最大值){
if(text.indexOf(match,n)!=-1){
i=text.indexOf(匹配,n);
n=i+match.length;
++火柴
}
}
//在第二次匹配的要查找的单词后插入're'`
var re=text.slice(0,i+match.length)+txt;
$(“div”).text(re+text.slice(i))

单词查找abc def单词查找ghi单词查找

这正是我想要的。我想我可以做我需要帮助的部分。查找字符串出现的次数和插入文本是两个独立的函数,实际上并不相关。我应该说得更具体一些,我是懒惰的,对内容重复使用变量,而不是为了这个单独的目的再次创建它。@D.Can“查找字符串出现的次数和插入文本是两个单独的函数,并不真正相关。”
循环检查匹配项,
i+match.length
应提供
text
max
匹配项的最后一个字符的索引;可以使用
.slice()
文本中引用此索引
$(cSearch).splice( insertLocation, -1 ).text( "Sample Text" );