【问题标题】:Add Text At Location from indexOf在 indexOf 的位置添加文本
【发布时间】:2015-12-06 02:36:55
【问题描述】:

我正在根据字符串出现的次数在某些 wordpress 帖子的底部插入文本。我已经设法通过追加将文本添加到底部,但我想使用 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');
        }
    }

以下是我将如何获得我想要插入的位置:

var insertLocation = cSearch.indexOf('Show what ya');

如何将“示例文本”拼接到 insertLocation 指定的位置?

我发现了一些关于将 polyfil 用于 .splice 的信息,但我不确定它是否适用。使用它如:

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

有人可以建议一种方法吗?谢谢!

【问题讨论】:

    标签: javascript jquery wordpress


    【解决方案1】:

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

    var text = $("div").text(),
      match = "Words To Find",
      txt = " Sample Text ",
      matches = 0,
      n = 0,
      // `max` : total number of `matches` before inserting `txt`
      max = 2;
    while (matches < max) {
      if (text.indexOf(match, n) !== -1) {
        i = text.indexOf(match, n);
        n = i + match.length;
        ++matches
      }
    }
    // insert `re` after second match of `"Words To find"`
    var re = text.slice(0, i + match.length) + txt;
    $("div").text(re + text.slice(i));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    </script>
    
    <body>
      <div>Words To Find abc def Words To Find ghi Words To Find</div>
    </body>

    【讨论】:

    • 这与我要找的很接近。我想我可以通过切片来完成我需要帮助的部分。查找字符串出现的次数和插入文本是两个独立的函数,并不真正相关。我应该更具体一点,我很懒惰并为内容重用变量,而不是为了这个单独的目的再次创建它。
    • @D.Can "查找字符串出现的次数和插入文本是两个独立的函数,并不真正相关。" while 循环检查匹配, i + match.length 应该提供max 匹配在text 内的最后一个字符的索引;可以使用.slice() 在text 中引用此索引
    猜你喜欢
    • 2022-11-10
    • 2020-03-06
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多