如何过滤特定标签内的匹配项?
我试图替换使用 TinyMCE 增强的输入字段中出现的所有文本,每次用户按下空格键时都会发生这种情况(类似于 Word 中的自动更正功能)。
我遇到的问题是,当替换的字符串包含触发器时,它会不断地一次又一次地替换它。 例如,将“hello”替换为
<span class="replaced">hello world</span>
它将再次替换为
<span class="replaced"><span class="replaced">hello world</span> world</span>
因此,我必须编写一个正则表达式来过滤掉已替换文本中的匹配项。
你能帮我一下吗?
这是我当前的代码:
for (r in autocorrect_replacements) {
if (newHtml.indexOf(autocorrect_replacements[r][0]) > -1) {
replacement_html = '<span class="replaced">'+autocorrect_replacements[r][1] + '</span>';
newHtml = newHtml.replace(autocorrect_replacements[r][0],replacement_html);
ed.setContent(newHtml);
}
我不喜欢正则表达式,但我认为在这种情况下这是正确的解决方案。
I'm trying to replace all ocurrences of a text in an input field which enhanced with TinyMCE, this has to occur every time the user presses the spacebar (similar to the autocorrect feature in Word).
The problem I have is when the replaced string contains the trigger, it keeps replacing it again and again.
For example replacing "hello" with
<span class="replaced">hello world</span>
It will replace it again as
<span class="replaced"><span class="replaced">hello world</span> world</span>
So I have to write a regexp to filter out matches in text that has already been replaced.
Can you help me out?
This is my current code:
for (r in autocorrect_replacements) {
if (newHtml.indexOf(autocorrect_replacements[r][0]) > -1) {
replacement_html = '<span class="replaced">'+autocorrect_replacements[r][1] + '</span>';
newHtml = newHtml.replace(autocorrect_replacements[r][0],replacement_html);
ed.setContent(newHtml);
}
I'm not a fan of regular expressions, but I think it's the correct solution in this case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
获取跨度的正则表达式为
/.*<\/span>/
。不确定它是否是正确的解决方案。你可以这样做:
The regex to get the span would be
/<span class="replaced">.*<\/span>/
. Not sure if its the right solution.You can do something like this: