JavaScript、Django 和 Google App Engine - 替换文本

发布于 2024-10-02 00:37:35 字数 822 浏览 1 评论 0原文

我的目标是使用 JS 将工具提示(包含定义)与客户端的某些单词相关联。
文本是使用 Django/Python(来自 GAE 数据存储)生成的。
为了实现这一点,我需要扫描文本块中的多个需要定义的关键字,并为工具提示动态创建一个 html“标题”。

我一次成功地完成了一个关键字的操作,但是,我似乎无法在同一文本块中搜索和替换多个值(当我尝试使用 django forloop 来完成时,整个原始字符串每个替换命令出现一次 - 见下文)。

我的代码:

    var str="<p>Paragraph of text containing key words such as test1 and test2!  </p>";
    {% for i in thing %}
    document.write(str.replace(/{{i.word}}/gi, "<strong><a title='{{i.tooltip}}'> {{i.word}}</a></strong>"));
    {% endfor %}

这会导致:

“包含关键字的文本段落,例如keyword1和keyword2!
包含关键词(例如keyword1和keyword2)的文本段落!”

我想要的输出是:

“包含关键字的文本段落,例如 keyword1keyword2!”

任何帮助将不胜感激,我对 JS 的了解非常有限。

My goal is to associate a tooltip (containing a definition) to certain words on the client side using JS.

The text is generated with Django/Python (from a GAE datastore).

To accomplish this, I need to scan a block of text for multiple key words that require definitions and dynamically create a html 'title' for the tooltip.

I have succesfully done this for one key word at a time, however, I seem to be unable to do a search for and replace multiple values within the same block of text (when I try to accomplish with a django forloop, the entire original string appears once for each replace command - see below).



My code:

    var str="<p>Paragraph of text containing key words such as test1 and test2!  </p>";
    {% for i in thing %}
    document.write(str.replace(/{{i.word}}/gi, "<strong><a title='{{i.tooltip}}'> {{i.word}}</a></strong>"));
    {% endfor %}

This results in:

"Paragraph of text containing key words such as keyword1 and keyword2!


Paragraph of text containing key words such as keyword1 and keyword2!"



My desired output is:

"Paragraph of text containing key words such as keyword1 and keyword2!"

Any assistance would be greatly appreciated, I have a very limited knowledge in JS.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

残疾 2024-10-09 00:37:35

最简单的方法是在 Django for 循环中简单地构建字符串,每次替换它,然后只在最后输出它:

{% for i in thing %}
str = str.replace(/{{i.word}}/gi, "<strong><a title='{{i.tooltip}}'> {{i.word}}</a></strong>"));
{% endfor %}
document.write(str);

The easiest way to do this would be to simply build up the string within the Django for loop, replacing on it each time, then only outputting it at the end:

{% for i in thing %}
str = str.replace(/{{i.word}}/gi, "<strong><a title='{{i.tooltip}}'> {{i.word}}</a></strong>"));
{% endfor %}
document.write(str);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文