Skip to content Skip to sidebar Skip to footer

JQuery Find/replace Without Changing Original Text

Is there a way in jQuery to find a string of text in jQuery and not replace it with something else but wrap that text with an element so when the script is finished it spits out th

Solution 1:

Altering page content is not, in general, as simple as replacing the html() markup with regex. All such attempts will fail where there is matched text in the markup itself, can fail when the browser chooses to serialise its DOM in a way that doesn't meet your expectations, and at best, when it does work, still forces you to serialise and re-parse all searched text, which is slow and destroys all non-serialisable information, such as form field values, JavaScript references and event handlers. You can get away with that for simple low-level elements, but against a container like <body> it'd be awful.

Better: instead of hacking at an HTML string, stick with the live DOM nodes, searching for Text nodes that match your requirements and doing the replacements on the straight text node data. Here's some plain JS code to do that (I guess you could put it in a plugin if you wanted.)

// Utility function to find matches in an element's descendant Text nodes,
// calling back a function with (node, match) arguments. The `pattern` can
// be a string, for direct string matching, or a RegExp object (which must
// be a `g`lobal regex.
//
function findText(element, pattern, callback) {
    for (var childi= element.childNodes.length; childi-->0;) {
        var child= element.childNodes[childi];
        if (child.nodeType==1) {
            var tag= child.tagName.toLowerCase();
            if (tag!=='script' && tag!=='style' && tag!=='textarea')
                findText(child, pattern, callback);
        } else if (child.nodeType==3) {
            var matches= [];
            if (typeof pattern==='string') {
                var ix= 0;
                while (true) {
                    ix= child.data.indexOf(pattern, ix);
                    if (ix===-1)
                        break;
                    matches.push({index: ix, '0': pattern});
                }
            } else {
                var match;
                while (match= pattern.exec(child.data))
                    matches.push(match);
            }
            for (var i= matches.length; i-->0;)
                callback.call(window, child, matches[i]);
        }
    }
}

Example usage with a plain string search term:

// Replace “World to” string in element text with <i>-wrapped version
//
var element= $('#construct_version')[0];
findText(element, 'World to', function(node, match) {
    var wrap= document.createElement('i');
    node.splitText(match.index+match[0].length);
    wrap.appendChild(node.splitText(match.index));
    node.parentNode.insertBefore(span, node.nextSibling);
});

Solution 2:

You can just use .replace(), for example:

var str = "Hello world to all people";
str = str.replace(/(world to all)/g, "<i>$1</i>");

You can give it a try here applied to say the html of an element:

$("span").html(function(i, t) {
    return t.replace(/(world to all)/g, "<i>$1</i>");
});

Solution 3:

I think you might use javascript:

var t= "Hello world to all people";
var output = t.replace("world to", "<i>world to</i>"));
alert(output);

Solution 4:

This is simple. Just do a jQuery .replace() function.

Here is a jsFiddle

http://jsfiddle.net/HZVs8/

The only issue with this method is that if you have any other words with the string "id" in them, it will convert those too. If the words are like "Project id", with a space, and not "Project-id" or "ProjectId", this method can be used like this:

$("body").html(function(i, x) {
return x.replace(/( id)/g, "ID");
});​

Make sure there is a space before the first id or it will select EVERY word that had the letters "id" in them.


Solution 5:

I wrote this below function long back, but it may not be so efficient but it works good.

categoryname is the string and userinput is the string you want to highlight, I want to wrap it over bold, you can change to li

function GetHighlightedString(categoryname,userinput) {
    userinput=TrimSS(userinput);
    var tempToSearch=categoryname.toLowerCase(); // to take care of case issue.
    var mysearchTemp=userinput;
    var mytemppos = tempToSearch.indexOf(mysearchTemp.toLowerCase());
    var finalstring=categoryname;
    var str1,str2,str3;
    str1=tempToSearch.substring(0,mytemppos);

    str2=tempToSearch.substring(mytemppos, mytemppos+userinput.length);

    if(userinput.toLowerCase()==str2) 
    {
        finalstring=str1 + '<b>';
        finalstring=finalstring+str2+'</b>';
    }
    else
    {
        finalstring= str1+str2;
    } 

    str3=tempToSearch.substring(mytemppos+userinput.length);
    finalstring=finalstring+str3;
    return finalstring;
}

Post a Comment for "JQuery Find/replace Without Changing Original Text"