JQuery search / replace without changing source text

Is there a way in jQuery to find a line of text in jQuery and not replace it with something else, but wrap this text with an element, so when the script ends, it spits out the source text with the line of text wrapped.

Example:

Original text

"Hello world to all people" 

Search line

 "world to" 

Replace <i></i>

Final conclusion

 "Hello <i>World to</i> all people" 

Thanks in advance for your help!

Type of working code:

 function highlightChild(child) { $(childElements[child]).text(""); console.log(child); $('.child_element_' + child).bind('textselect', function(e){ var selection = e.text; var str = $("#construct_version").text(); var wrap = jQuery(childElements[child]).text(selection); var re = new RegExp("" + selection + "", "g"); console.log(str.replace(selection, function(match, key, val){ console.log(match); console.log(key); console.log(val); jQuery(childElements[child]).text(val) })); }); } 

The above code replaces, but where it actually replaces it as undefined.

So, if the source line is the Hello world for everyone, and I want to replace the world with <b>world to</b> , it shows in console.log as Hello undefined all

+5
source share
5 answers

Changing the contents of a page is generally not as simple as replacing html() markup with regex. All such attempts will fail if there is consistent text in the markup itself, it may fail when the browser decides to serialize its DOM in a way that does not meet your expectations, and in the best case, when it works, it still forces you to serialize and repeatedly analyze all the searched text that is slow and destroys all non-serializable information, such as form field values, JavaScript links, and event handlers. You can avoid this for simple low-level elements, but against a container like <body> would be awful.

Better: instead of hacking an HTML string, stick to live DOM nodes, look for Text nodes matching your requirements, and replace the direct text data with a node. Here is some simple JS code for this (I think you could put it in a plugin if you want.)

 // Utility function to find matches in an element 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]); } } } 

Usage example with a regular 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); }); 
+13
source

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

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

Here you can try to say html of the element:

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

I think you can use javascript:

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

It's simple. Just execute the jQuery.replace () function.

Here is jsFiddle

http://jsfiddle.net/HZVs8/

The only problem with this method is that if you have other words with the string "id" in them, they will also convert them. If the words are similar to "Project ID" with a space and not "Project-id" or "ProjectId", this method can be used as follows:

 $("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 has the letters "id" in it.

0
source

I wrote this function below, but it may not be as efficient, but it works well.

categoryname is the string, and userinput is the string you want to highlight, I want to wrap it in bold, you can change it 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; } 
-1
source

Source: https://habr.com/ru/post/888174/


All Articles