JavaScript、Django 和 Google App Engine - 替换文本
我的目标是使用 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)的文本段落!”
我想要的输出是:
“包含关键字的文本段落,例如 keyword1 和 keyword2!”
任何帮助将不胜感激,我对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的方法是在 Django for 循环中简单地构建字符串,每次替换它,然后只在最后输出它:
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: