How do I do a case insensitive search for a word and convert it to a hyperlink using jquery?

空扰寡人 提交于 2020-01-06 14:39:16

问题


I want to convert certain key words into affiliate links on my website. I do not want to hand-code each one of those links in every page. So I'm looking for a Javascript/Jquery based solution where using a given a list of keywords and corresponding URLs (a two dimensional array), on page load, these keywords are 'URLified' using their corresponding URLS.

I found this comment Find text string using jQuery? which has the code for a case insensitive search, but it URLifies the whole text node instead of just the word.

I could use something like the code below. But the problem is that it will URLify keywords inside <pre> elements too. I want them URLified inside just <p> elements.

<script type="text/javascript">
(function($) {
  var thePage = $("body");
  thePage.html(thePage.html().replace(/testing/ig, '<a href="http://testing.com">testing</a>')); 
})(jQuery)
</script>

For eg:

<p>I'm going to test urlification</p>
<pre>
function test() {
alert(' test ');
}
</pre>

should change to

<p>I'm going to <a href="test123.com">test</a> urlification</p>
<pre>
function test() {
alert(' test ');
}
</pre>

回答1:


1. Here is the jQuery plugin which replaces text snippets

/**
* jQuery plugin to replace text strings
*
* Taken from @link http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/
*/

$.fn.replaceText = function( search, replace, text_only ) {
return this.each(function(){
        var node = this.firstChild,
        val, new_val, remove = [];
        if ( node ) {
            do {
              if ( node.nodeType === 3 ) {
                val = node.nodeValue;
                new_val = val.replace( search, replace );
                if ( new_val !== val ) {
                  if ( !text_only && /</.test( new_val ) ) {
                    $(node).before( new_val );
                    remove.push( node );
                  } else {
                    node.nodeValue = new_val;
                  }
                }
              }
            } while ( node = node.nextSibling );
        }
        remove.length && $(remove).remove();
    });
};

2. Here is the code which you can use to achieve the replacements

// the array of affiliate links
var affiliates = [
        ['google', 'http://www.google.com/'],
        ['bing', 'http://www.bing.com/'],
        ['yahoo', 'http://www.yahoo.com/']
    ],
    $p = $('p'), // the selector to search text within
    i = 0, // index declared here to avoid overhead on the loop
    size = affiliates.length, // size of the affiliates array 
                              // again declared here to avoid overhead
    reg; // the regex holder variable

// loop over all the affiliates array
for(i; i < size; i++){
    // create a regex for each affiliate
    reg = new RegExp('('+affiliates[i][0]+')','gi');

    // finally replace the string with the link
    // NOTE: do not forget to include the aforementioned plugin before this code,
    // otherwise this won't work
    $p.replaceText(reg, '<a href="'+affiliates[i][2]+'">$1</a>');
}

Here is a demo

3. You need to make some changes

All you have to do is change the jQuery selector, and the affiliates array. The rest will be taken care of by the plugin. The plugin is smart enough not to replace the element's attributes.




回答2:


Something like -

var foundin = $('p:contains("I am a simple string")');
foundin.each(function () {
    var linktext = $(this).html().replace('I am a simple string','<a href="">I am a simple string</a>');
    $(this).html(linktext);
});  

Or using your example -

var foundin = $('p:contains("testing")');
foundin.each(function () {
    var linktext = $(this).html().replace(/testing/ig, '<a href="http://testing.com">testing</a>'));
    $(this).html(linktext);
});  

Technique taken from - Find text string using jQuery?




回答3:


Have you tried this:

Put them in span with class "URLify" and based on what data you get just replace the innerText of the span by creating the URL on the fly with your code

Here is some text with this <span class="URLify">DataItem</span> to be search and replaced with URL or just to be URLified

In your jQuery you can do something like this (not tested)

var URL = "http://www.myapp.com/ListOfItems/"; //the url to use or append item to

$('.URLify').wrapInner('<a href="'+URL+'"></a>');

or if you want to append "DataItem" to ".../ListOfItems/" you can do that too...




回答4:


JQuery will not give you text nodes. You will have to check for text nodes explicitly using a JQuery filter, of by just traversing the DOM (which is probably faster in this case). An example is given here on SO.



来源:https://stackoverflow.com/questions/6965722/how-do-i-do-a-case-insensitive-search-for-a-word-and-convert-it-to-a-hyperlink-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!