Similar to: Search For Words, Replace With Links. However, I would rather not have the full hyperlink's URL visible, but instead have only the appearance of a hyperlink visible to the end-user. --- I also can't figure out how to use the replace()
-JS-function, like used in the following post: How to replace all occurrences of a string in JavaScript?, for this same specific issue. --- Also similar to a JS-question: Link terms on page to Wikipedia articles in pure JavaScript, but I guess the answer given there can not, up front, differentiate between ambiguous terms.
How to auto-link every occurence of single words or word sequences to their respective predefined URL's?
In (a) certain HTML-page(s), is it possible to:
- Predefine manually; or automatically (Cf: Wiki-api) a list of single words and their respective (i.c. Wikipedia)-articles;
- such that every (such coupled) word in a document automatically receives the predefined link to the respective (i.c. Wikipedia)-article.
EXAMPLE:
(1) Wherever the word cell occurs, this word should receive the link: ...wiki/cell, to give the following result: a cell is but a cell.
So, what I actually would like is to mimic what is actually happening within any Wikipedia-article itself (although I don't know whether this is automated there).
Any help would be greatly appreciated.
Starting with the question you linked, it's pretty easy to modify it to achieve your goal. So first assuming we have a list of phrase and links like this:
var words = [
{ word: 'foo', link: 'http://www.something.com' },
{ word: 'Something Else', link: 'http://www.something.com/else' ]
];
We can iterate over that list replacing any occurrence in the document, but including the word we are searching for in the text we are inserting. I've added in a tooltip to this too to show an example of what else you can do.
$(function() {
$.each(words,
function() {
var searchWord = this.word;
var link = this.link;
$('body:contains("' + searchWord + '")').each(function() {
var newHtml = $(this).html().replace(searchWord,
'<a class="wikilink" title="here is a link to Wikipedia" href="'+link+'">' + searchWord + '</a>');
$(this).html(newHtml);
});
}
);
});
And a working example: http://jsfiddle.net/yxhk1fcd/10/
来源:https://stackoverflow.com/questions/28398112/auto-hyperlink-every-occurence-of-a-certain-word-or-word-sequence-to-predefine