Getting HTML markup in a string compiled - javascript

I'm trying to give a HTML element a markup but it outputs in a string.
My code:
var inputString = tweet.text;
var findme = screen_name;
tweet.text = inputString.replace(screen_name, "<span class='searched'>" + screen_name + "</span>")

You're likely experiencing this issue because you're setting the string on the UI as text, not HTML. Elements have an innerHTML property which will create child elements if necessary.
DEMO
var inputString = "Hello Daniel!";
var findme = "Daniel";
var replacedString = inputString.replace(findme, "<span class='searched'>" +
findme + "</span>");
document.querySelector('#output').innerHTML = replacedString;

Try
.innerHTML
.replace outputs strings, not html
EDIT
var inputString = tweet.text;
var findme = screen_name;
tweet.text = inputString.replace(screen_name, "<span class='searched'>" + screen_name + "</span>")
SomeHTMLObject.innerHTML=tweet.text;

Found out the solution myself:
In the HTML page, you can should use HTML-escape. So you have to use {{{ variable }}} instead of {{ variable }}
Simple solution, should have thought about that..

Related

try to show html tags as text with innerHTML

I have a string that contains HTML tags.
I want to render as an HTML element only the span tags aka <span></span>.
every other tag that is not a span tag should be treated as regular text.
The result I'm trying to achieve is to color any text that I want even if it contains HTML tags.
I fail.
is there any other technique that I can try or a workaround?
var problem = ["<h1>","</h1>"];
var red_text = "<span style='color:red'>i am red </span>";
var green_text = "<span style='color:green'>" +
problem[0] +
"i am green" +
problem[1] +
"</span>";
//the real result should have <h1> </h1>
var expected_text = red_text + "<span style='color:green'>|h1|i am green|/h1|</span>";
document.getElementById("demo").innerHTML = red_text + green_text;
document.getElementById("expected").innerHTML = expected_text;
HTML and JavaScript code at :
https://jsfiddle.net/ytLftxww/1/
You need to use HTML entities to escape the < and > in those tags.
For example: "<span style='color:green'><h1>i am green</h1></span>"
See the fiddle: https://jsfiddle.net/ytLftxww/1/
var problem = ["<h1>","<h1>"];
does unescaping the < > work for you?
updated fiddle
You can use &lt for < and & &gt for >.

Javascript not able to replace text with new Text with html

I trying to replace text with new text inside a html tag like:
text = " hello how are you? " ;
newText = "<h1>hello how are you? </h1> " ;
This is my code:
//replacer holds the html element
var replacer = document.getElementById("#"+id);
var newElement = "<span style='font-size:100px;' id='one4'>"+selectedinnerText+"</span>";
//selectedinnerText holds the text to be replaced
alert(selectedinnerText + " "+ newElement );
//This below line is not working properly
replacer.innerHTML = replacer.innerHTML.replace(selectedinnerText,newElement);
Your issue is, when you are getting an element by its id in JavaScript, you do not need # infront of the id name.
var replacer = document.getElementById(id);
So, the reason why you cannot set the innerHTML of the replacer element is because there is no element stored in the variable right now.
The correct code should be
var replacer = document.getElementById(id);// no # needed here
var newElement = "<span style='font-size:100px;' id='one4'>"+selectedinnerText+"</span>";
alert(selectedinnerText + " "+ newElement );
replacer.innerHTML = replacer.innerHTML.replace(selectedinnerText,newElement);

Extracting anchor text from anchor tag with JavaScript

I recently posted on question for extracting anchor text from anchor tag using javascript. I got one answer for it.
However the code is working in IE and Chrome but not in Firefox.
function extractText(){
var docId = "10";
var cId = "13";
var dName = "ASPIRIN/COUMARIN";
var anchText = "<a target=\"_blank\" href=hello?docId=" + docId + "&cId=" + cId +">" + dName +"</a>";
var str1 = document.createElement('str1');
str1.innerHTML = anchText;
var anc = str1.innerText;
alert(anc);
return anc;
}
I suppose the property of innerText or innerHTML or both is not working in firefox. Can you please help where the above code work for IE, Chrome, Firefox etc.
textContent by the W3C standard used in Firefox is the alternative for innerText
Firefox doesn't seem to support the innerText property, preferring to use the W3C's standard of textContent:
function extractText() {
var docId = "10";
var cId = "13";
var dName = "ASPIRIN/COUMARIN";
var anchText = "<a target=\"_blank\" href=hello?docId=" + docId + "&cId=" + cId + ">" + dName + "</a>";
var str1 = document.createElement('str1');
str1.innerHTML = anchText;
var anc = (str1.innerText || str1.textContent);
console.log(anc);
return anc;
}
extractText();
JS Fiddle demo.
Assuming you want to avoid checking both properties on every call, you could simply check which the browser supports, with:
var textProperty = 'textContent' in document ? 'textContent' : 'innerText';
And then use that as follows:
var anc = str1[textProperty];
JS Fiddle demo.
References:
innerText property.
Node.textContent.

Javascript - Regex : How to replace id in string with the same id plus number?

I have a string with multiple elements with id's like below:
var data = "<div id='1'></div><input type='text' id='2'/>";
Now I'm using this regex to find all the id's in the string:
var reg = /id="([^"]+)"/g;
Afterwards I want to replace all those id's with a new id. Something like this:
data = data.replace(reg, + 'id="' + reg2 + '_' + numCompare + '"');
I want reg2, as seen above, to return the value of the id's.
I'm not too familiar with Regular Expressions, so how can I go about doing this?
Instead of using regex, parse it and loop through elements. Try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = document.createElement("div"),
i, cur;
div.innerHTML = data;
function updateId(parent) {
var children = parent.children;
for (i = 0; i < children.length; i++) {
cur = children[i];
if (cur.nodeType === 1 && cur.id) {
cur.id = cur.id + "_" + numCompare;
}
updateId(cur);
}
}
updateId(div);
DEMO: http://jsfiddle.net/RbuaG/3/
This checks to see if the id is set in the first place, and only then will it modify it.
Also, it is safe in case the HTML contains a comment node (where IE 6-8 does include comment nodes in .children).
Also, it walks through all children of all elements. In your example, you only had one level of elements (no nested). But in my fiddle, I nest the <input /> and it is still modified.
To get the get the updated HTML, use div.innerHTML.
With jQuery, you can try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = $("<div>"),
i, cur;
div.append(data);
div.find("[id]").each(function () {
$(this).attr("id", function (index, attr) {
return attr + "_" + numCompare;
});
});
DEMO: http://jsfiddle.net/tXFwh/5/
While it's valid to have the id start with and/or be a number, you should change the id of the elements to be a normal identifier.
References:
.children: https://developer.mozilla.org/en-US/docs/DOM/Element.children
.nodeType: https://developer.mozilla.org/en-US/docs/DOM/Node.nodeType
jQuery.find(): http://api.jquery.com/find/
jQuery.attr(): http://api.jquery.com/attr/
jQuery.each(): http://api.jquery.com/each/
Try using
.replace(/id='(.*?)'/g, 'id="$1_' + numCompare + '"');
Regex probably isn't the right way to do this, here is an example that uses jQuery:
var htmlstring = "<div id='1'></div><input type='text' id='2'/>";
var $dom = $('<div>').html(htmlstring);
$('[id]', $dom).each(function() {
$(this).attr('id', $(this).attr('id') + '_' + numCompare);
});
htmlstring = $dom.html();
Example: http://jsfiddle.net/fYb3U/
Using jQuery (further to your commments).
var data = "<div id='1'></div><input type='text' id='2'/>";
var output = $("<div></div>").html(data); // Convert string to jQuery object
output.find("[id]").each(function() { // Select all elements with an ID
var target = $(this);
var id = target.attr("id"); // Get the ID
target.attr("id", id + "_" + numCompare); // Set the id
});
console.log(output.html());
This is much better than using regex on HTML (Using regular expressions to parse HTML: why not?), is faster (although can be further improved by having a more direct selector than $("[id]") such as giving the elements a class).
Fiddle: http://jsfiddle.net/georeith/E6Hn7/10/

jQuery replace hyphens with spans for blogger date header

I'm looking to customize the default date header in blogger with jQuery.
The original output is:
<h2 class='date-header'>2011-01-20</h2>
I want to wrap the YYYY, MM, and DD in spans so I can manipulate them as child nodes.
The result would be:
<h2 class='date-header'><span class="dhy">2011</span><span class="dhm">01</span><span class="dhd">20</span></h2>
Each attempt of mine adds extra tags so it's a nested mess.
Anybody have a good solution?
Here's a nice functional solution:
$('.date-header').html(function() {
var txt = $(this).text();
var classes = ['dhy', 'dhm', 'dhd'];
$(this).html($.map(txt.split(/-/), function(val) {
return $('<span/>', {'class': classes.shift()}).text(val)[0];
}));
});
http://jsfiddle.net/ThiefMaster/WdRAw/
If it always has the same format of YYYY-MM-DD then you could use split to get the elements, loop through them, create your output HTML then add that as the HTML of the h2.
$(function()
{
$(".date-header").each(function()
{
var arrDate = $(this).text().split("-");
var strOut = '<span class="dhy">'+arrDate[0]+'</span>-';
strOut+= '<span class="dhm">'+arrDate[1]+'</span>-';
strOut+= '<span class="dhd">'+arrDate[2]+'</span>';
$(this).html(strOut);
});
});
And a fiddle: http://jsfiddle.net/ahallicks/xGa2J/2/
I think this should do it:
var header = $('.date-header');
var d = header.text().split('-');
header.html('<span class="dhy">' + d[0] + '</span><span class="dhm">' + d[1] + '</span><span class="dhd">' + d[2] + '</span>');

Categories