简体   繁体   中英

Replace string - How to replace each word once

I have an xml dictionary as shown below.

<word definition="The primary income-earner in a household"&gtbread winner</word>
<word definition="One who wins, or gains by success in competition, contest, or gaming"&gtwinner</word>

Whenerver there is a word from dictionary in my html, that word will be replaced with link and definition as title. When link is hovered, user should see the definition.

var allwords = xmlDoc.getElementsByTagName("word");
for (var i=0; i<allwords.length; i++)
    {
            var name = allwords[i].lastChild.nodeValue;

            var linked = '<a href ="#" title="' +  allwords[i].lastChild.nodeValue + ': ' + allwords[i].getAttribute("definition") + '">' + allwords[i].lastChild.nodeValue + '</a>'; 
    }

Here is my replacer

function replacer(oldstring, newstring) {
document.body.innerHTML = document.body.innerHTML.replace(oldstring, newstring);
}

But problem is once changes to linked form, also changes since includes , winner changes twice, and all the code mixes up. 改变为关联形式,也是变化,因为包括 ,获胜者改变两次,并且所有代码混合起来。

I am asking if there is a way, once changes should not change anymore. 改变不应再改变。

Thanks in advance!

What about something like this:

for (var i=0; i<allwords.length; i++)
{
    if(allwords[i].firstChild.name == 'a') {
        // This word has been linked already, skip it
    }

    // your code
}

You need some kind of sentry to prevent processing a term that's already been processed. I'd recommend wrapping the replaced terms with another element (not clear on how your html is structured, so I'm not sure what would work here, but a span would be the simplest way in normal html). Then your logic would just skip replacing words that had a parent element of whatever you decided to wrap it with.

您需要遍历匹配的文本节点,并且只替换那些没有A标记作为DOM中的祖先的节点。

Try function strtr ($text, $fromList, $toList). It should replace each term once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM