I have a ajax response object say 'var data;' .
It contains html content.
In it there is table with id='table123'.
I want to replace word say 'sample' with 'SAMPLE' form inside that table in variable 'data'.
I want to replace all occurrence of the word 'sample'using javascript or jquery.
You can use javascript replace mathod,
data.replace(/sample/g, "SAMPLE");
Update due to change in OP
var data = $(data);
changedHtml = data.find('#table123').html().replace(/sample/g, "SAMPLE");
data.find('#table123').html(changedHtml);
Create the table first and then replace the text.
// used "#id" for illustration purposes
$("#id").append( data );
var el = $('#table123');
var txt = el.html( el.html().replace(/sample/g, 'SAMPLE') );
Regarding the use of $(data) the jQuery docs state the following about passing a string into jQuery()
if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML.
So you might as well create the element in the first place and replace after.
Related
I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;
I have a XML mark-up/code like the following. I want to replace the text inside one of the tags (in this case <begin>...</begin>) using JavaScript or jQuery.
<part>
<begin>A new beginning</begin>
<framework>Stuff here...</framework>
</part>
The source is inside a textarea. I have the following code, but it is obviously not doing what I want.
code=$("xml-code").val(); // content of XML source
newBegin = "The same old beginning"; // new text inside <begin> tags
newBegin = "<begin>"+newBegin +"</begin>";
code=code.replace("<begin>",newBegin); // replace content
This is just appending to the existing text inside the begin tags. I have a feeling this can be done only using Regex, but unfortunately I have no idea how to do it.
You can use the parseXML() jQuery function, then just replace the appropriate node with .find()/.text()
var s = "<part><begin>A new beginning</begin><framework>Stuff here...</framework></part>";
var xmlDoc = $($.parseXML(s));
xmlDoc.find('begin').text('New beginning');
alert(xmlDoc.text());
http://jsfiddle.net/x3aJc/
Similar to the other answer, using the $.parseXML() function, you could do this:
var xml = $.parseXML($("xml-code").val());
xml.find('begin').text('The same old beginning');
Note that there is no need to replace a whole node, just change it's text. Also, this works if there are multiple <begin> nodes that need the text as well.
You can user regular expression but better dont do it. Use DOM parsers.
var code = $('xml-code').html(); // content of XML source
var newBegin = "The same old beginning"; // new text inside <begin> tags
var regexp = new Regexp('(<part>)[^~]*(<\/part>)', i);
code = code.replace(regexp, '$1' + newBegin + '$2');
I get some markdown text from a database. I am using Showdown.js to transform this markdown into HTML:
var showdown = new Showdown.converter();
var str = showdown.makeHtml(myDatabaseString);
When there is code embedded within the markdown, Showdown.js will wrap it nicely into <pre><code> tags, so str may look something like this:
<p>Some text bla</p><pre><code>Some code</pre></code><p>Text again</p>
Now I want make things prettier by syntax highlighting the code pieces using SyntaxHighlighter. It's important that in the end I get a string back that contains everything it had before, plus the additional HTML for formatting.
My approach to this was the JQuery's ability to manipulate DOM:
$(str).each(function() {
// or can I select only pre within $(str) directly?
// everything I tried so far to do that failed miserably
if($(this).is('pre')) {
var code = $('code', $(this)).text();
// brush is my SyntaxHighlighter brush that I created earlier
$('code', $(this)).text(brush.getHtml(code));
// when I console.log($('code', $(this))) now, everything worked
// out perfectly
}
});
// but now I lost all my changes for some reason :-(
return str; // I need to return this as a string again
Am I on the right way? How can I keep the changes I make within my .each loop?
That's because you are creating a jQuery object that has nothing to do with str variable, you should use the created jQuery object. In fact you are modifying the elements of the created jQuery object and returning the original/unchanged str variable. I'd suggest:
// Creating a wrapper element
// and setting it's content by using str variable
var $wrapper = $('<div/>').html(str);
// Modifying descendant pre elements
$wrapper.find('pre').each(function(){
// implementing the logic
});
// Getting modified HTML content of the created wrapper element
str = $wrapper.html();
I tried to use the method data (jQuery 1.7.1) in this code:
var q = '<div class="form-error-marker"></div>';
var t = $(q).data('message', message).insertAfter(el);
and it does not work.
Note that this works:
var t = $(q).attr('data-message', message).insertAfter(el);
Why does the first variant not work?
EDIT: insertAfter works correctly and new div is added after el (which is instance of one element which I get by getElementById() function; long story short I have a library that I extend).
When I say 'it does not work' I mean that the attribute 'data-message' is not stored.
Using data like that sets an arbitrary piece of data for this node; it doesn't add a new data- attribute. Just add the attribute with the attr function, and then access it with data
var q = $('<div class="form-error-marker"></div>').attr("data-message", message);
Now access it like this:
var message = q.data("message");
Here's a fiddle
When you use jQuery.data you don't change element attributes, instead your data saved in $.cache.
So if you want to change element attributes use jQuery.attr, when you want to save some info use jQuery.data
I understand so far that in Jquery, with html() function, we can convert HTML into text, for example,
$("#myDiv").html(result);
converts "result" (which is the html code) into normal text and display it in myDiv.
Now, my question is, is there a way I can simply convert the html and put it into a variable?
for example:
var temp;
temp = html(result);
something like this, of course this does not work, but how can I put the converted into a variable without write it to the screen? Since I'm checking the converted in a loop, thought it's quite and waste of resource if keep writing it to the screen for every single loop.
Edit:
Sorry for the confusion, for example, if result is " <p>abc</p> " then $(#mydiv).html(result) makes mydiv display "abc", which "converts" html into normal text by removing the <p> tags. So how can I put "abc" into a variable without doing something like var temp=$(#mydiv).text()?
Here is no-jQuery solution:
function htmlToText(html) {
var temp = document.createElement('div');
temp.innerHTML = html;
return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}
Works great in IE ≥9.
No, the html method doesn't turn HTML code into text, it turns HTML code into DOM elements. The browser will parse the HTML code and create elements from it.
You don't have to put the HTML code into the page to have it parsed into elements, you can do that in an independent element:
var d = $('<div>').html(result);
Now you have a jQuery object that contains a div element that has the elements from the parsed HTML code as children. Or:
var d = $(result);
Now you have a jQuery object that contains the elements from the parsed HTML code.
You could simply strip all HTML tags:
var text = html.replace(/(<([^>]+)>)/g, "");
Why not use .text()
$("#myDiv").html($(result).text());
you can try:
var tmp = $("<div>").attr("style","display:none");
var html_text = tmp.html(result).text();
tmp.remove();
But the way with modifying string with regular expression is simpler, because it doesn't use DOM traversal.
You may replace html to text string with regexp like in answer of user Crozin.
P.S.
Also you may like the way when <br> is replacing with newline-symbols:
var text = html.replace(/<\s*br[^>]?>/,'\n')
.replace(/(<([^>]+)>)/g, "");
var temp = $(your_selector).html();
the variable temp is a string containing the HTML
$("#myDiv").html(result); is not formatting text into html code. You can use .html() to do a couple of things.
if you say $("#myDiv").html(); where you are not passing in parameters to the `html()' function then you are "GETTING" the html that is currently in that div element.
so you could say,
var whatsInThisDiv = $("#myDiv").html();
console.log(whatsInThisDiv); //will print whatever is nested inside of <div id="myDiv"></div>
if you pass in a parameter with your .html() call you will be setting the html to what is stored inside the variable or string you pass. For instance
var htmlToReplaceCurrent = '<div id="childOfmyDiv">Hi! Im a child.</div>';
$("#myDiv").html(htmlToReplaceCurrent);
That will leave your dom looking like this...
<div id="myDiv">
<div id="childOfmyDiv">Hi! Im a child.</div>
</div>
Easiest, safe solution - use Dom Parser
For more advanced usage - I suggest you try Dompurify
It's cross-browser (and supports Node js). only 19kb gziped
Here is a fiddle I've created that converts HTML to text
const dirty = "Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>";
const config = { ALLOWED_TAGS: [''], KEEP_CONTENT: true, USE_PROFILES: { html: true } };
// Clean HTML string and write into the div
const clean = DOMPurify.sanitize(dirty, config);
document.getElementById('sanitized').innerText = clean;
Input: Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>
Output: Hello world Many other tags are stripped
Using the dom has several disadvantages. The one not mentioned in the other answers: Media will be loaded, causing network traffic.
I recommend using a regular expression to remove the tags after replacing certain tags like br, p, ol, ul, and headers into \n newlines.