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, 开发者_如何学Goit 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.
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:
for (r in autocorrect_replacements) {
if (newHtml.indexOf(autocorrect_replacements[r][0]) > -1) {
if (!(/<span class="replaced">.*<\/span>/.test(autocorrect_replacements[r][1]))){
replacement_html = '<span class="replaced">'+autocorrect_replacements[r][1] + '</span>';
newHtml = newHtml.replace(autocorrect_replacements[r][0],replacement_html);
ed.setContent(newHtml);
}
}
精彩评论