javascript - 用链接替换主题标签,它只替换字符串中的最后一个单词
问题描述
我正在尝试制作一个主题标签系统,所以我到达了编辑文本功能,如果用户键入主题标签词,我想用主题标签链接替换输入的编辑。所以我使用 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>");
});
}
}
解决方案
在我发布了这个问题之后,我继续尝试解决方案,直到我想出以下适用于所有案例标签的完美解决方案
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];
}
}
推荐阅读
- pyqt5 - PyQt5 获取具有多个值的输入
- puppeteer - 如何记录发送到 Puppeteer/Chrome 开发者的每个事件
- math - 使用 DrRacket(方案)在偶数个垫子上跳蛙
- azure - 如何将 Azure 测试计划与管道相结合?
- visual-studio - 如何使用 WSL 从 Bash 构建现有的仅限 Windows 的 Visual Studio 项目
- python - Python脚本调用api并返回json输出
- c# - pt-BR 的 Bot Framework Emulator 语言环境问题
- terminal - Iterm2 首选项:显示带有目录、日期和 git 的栏
- java - 一次不能发出一件物品,每次我发出一件物品时,它总是发出所有剩下的物品,而不是只发出一件物品
- mysql - Kubernetes mariadb 用户登录