本文介绍了替换字符串-如何一次替换每个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个xml字典,如下所示.
I have an xml dictionary as shown below.
<word definition="The primary income-earner in a household">bread winner</word>
<word definition="One who wins, or gains by success in competition, contest, or gaming">winner</word>
每当我的html中有一个字典中的单词时,该单词将被链接和定义作为标题替换.当链接悬停时,用户应该看到定义.
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 bread winner changes to linked form, also winner changes since bread winner includes winner, winner changes twice, and all the code mixes up.
I am asking if there is a way, once bread winner changes winner should not change anymore.
Thanks in advance!
推荐答案
<script type="text/javascript">
// here your own array from xml, sorted on length
var allwords = ["bread winner", "winner", "win", "w"];
function processString(line, index)
{
// search for the first occurence (case insensitive) in the line
var i = line.search(new RegExp(allwords[index], "i"));
if (i == -1)
{
// Not found
if (index < allwords.length-1)
{
// We have more words to find
return processString(line, index+1)
}
else
{
// This part ends here
return line;
}
}
else
{
// Word was found, split line into three parts
var leftpart = line.substr(0, i);
var word = line.substr(i, allwords[index].length);
var rightpart = line.substr(i + allwords[index].length);
var result = "";
//continue search with another word (if available)
//and the part is long enough
if (index < allwords.length-1)
if (leftpart.length>allwords[index+1].length)
result = processString(leftpart, index+1);
else
result = leftpart;
else
result = leftpart;
//insert here the description from xml
//the original word is preserved
result += word.link("www.yourdomain.com?word=" + word);
//continue search with the current word if the part is long enough
if (rightpart.length>allwords[index].length)
result += processString(rightpart, index);
else
result += rightpart;
//left+word+right
return result;
}
}
// test string
var str = "win Every bread Winner in the world! Winner win Every bread winner on earth winner!";
//start processing, just one call
str = processString(str, 0);
//this will show the result
document.write(str + "<br />");
//this will show the html
alert(str);
</script>
这篇关于替换字符串-如何一次替换每个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!