首页 > 解决方案 > 用链接替换主题标签,它只替换字符串中的最后一个单词

问题描述

我正在尝试制作一个主题标签系统,所以我到达了编辑文本功能,如果用户键入主题标签词,我想用主题标签链接替换输入的编辑。所以我使用 JavaScript 和 jQuery 来执行此操作,但问题是 for 循环仅替换字符串中的最后一个单词,而不是所有字符串都替换为链接。

// Turn hashtags into links
var discussionText = "#example #text #string #one #two #three #hashtag #word";
var wordsArray = discussionText.split(" ");

for (i = 0; i < wordsArray.length; i++) {
  console.log(i);
  if (wordsArray[i].indexOf('#') > -1) {
    var wordWithoutHashtag = wordsArray[i].replace("#", "");
    console.log(wordWithoutHashtag);
    $("#" + editDiscussionButtonId + "-" + editDiscussionButtonUserId + "-spanDiscussionEdit").html(function() {
      return $(this).text().replace(wordsArray[i], "<a href='search.php?sec=all&q=" + wordWithoutHashtag + "' class='hashtag_link'>" + wordsArray[i] + "</a>");
    });
  }
}

标签: javascriptjquery

解决方案


在我发布了这个问题之后,我继续尝试解决方案,直到我想出以下适用于所有案例标签的完美解决方案

var discussionText = "#example #text #string #one #two #three #hashtag #word";
var wordsArray = discussionText.split(" ");
                    var fullText = "";

                    for(i=0; i < wordsArray.length; i++) {

                        if (wordsArray[i].indexOf('#') > -1) {
                            var wordWithoutHashtag = wordsArray[i].replace("#", "");

                            var wordLink = wordsArray[i].replace(wordsArray[i], "<a href='search.php?sec=all&q="+wordWithoutHashtag+"' class='hashtag_link'>"+wordsArray[i]+"</a>");
                            fullText += " " + wordLink;
                            $("#"+editDiscussionButtonId+"-"+editDiscussionButtonUserId+"-spanDiscussionEdit").html(fullText);
                        } else {
                            fullText += " "+wordsArray[i];
                        }

                    }

推荐阅读