Viewing HTML string as HTML - javascript

I have some autogenerated html code highlighting some texts in my angularJS app. The line generating the html code is this one:
var replaced = original.replace(regEx, '<span style="background-color: red;">' + replacing + '</span>');
line[key + 'HL'] = replaced;
But writing this on template
<div><p>{{line.codeHL ? line.codeHL : line.code}} {{line.price}}</p></div>
shows this:
<span style="background-color: red;">GD5AU211</span> 102€
How can I force the evaluation of html code inside a string?
Also let's just say I can't use document.getElementById() for reasons.

Refer to this link. This may be what you seek:
AngularJS : Insert HTML into view
To enable html insertion into view you have to define html as trusted data using $sce.trustAsHtml()
Hope this would help.

if you are using angular 4 then use innerHTML
<div><p>
<div [innerHTML]="line.codeHL ? line.codeHL : line.code">
</div> {{line.price}}
</p></div>
if you are using angular 1 then use ng-bing-html
<div><p>
<div ng-bind-html="line.codeHL ? line.codeHL : line.code | cust">
</div> {{line.price}}
</p></div>
now create a cust filter like this
.filter('cust',function($sce){
return function(html){
return $sce.trustAsHtml(html)
}
})

Add <xmp> tag before your html that has to be displayed as text.
var replaced = original.replace(regEx, '<span style="background-color: red;"><xmp>' + replacing + '</xmp></span>');

Related

how to display a variable value along with the text in .html()

Hi I have a requirement of printing the value is the popup,
I have used the below code
"code"
$('#warning').html('<p style="font-size: 12px;padding-top: 13px;">The updated list value is <p>' + var11);
but i wanted the value 500 to be displayed next to the text in the same line
can some one help me out with this
Thanks
Just need to concenenate with + inside the <p> tag.
var var11 = 500
$('#warning').html('<p style="font-size: 12px;padding-top: 13px;">The updated list value is ' + var11+'<p>' );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="warning"></div>
Hope this helps
Just add the variable to the text of <p> tag also you can use Template strings:
$('#warning').html(`<p style="font-size: 12px;padding-top: 13px;">The updated list value is ${var11} <p>` );
Get your variable inside the p tag :
$('#warning').html('<p style="font-size: 12px;padding-top: 13px;">The updated list value is' + var11 + ' <p>');

Using regex with javascript on nodejs find html attribute and prepend something to its value

I have some markup in JS as follows:
<div class="col-sm-4">
<span id="some-media" class="media">Text</span>
</div>
I would like to select the class attribute of the span and prepend its value with lets say the characters: "::". So after the regex replace i would end up with:
<div class="col-sm-4">
<span id="some-media" class="::media">Text</span>
</div>
EDIT: Note that the order of the attributes in the HTML element is variable so my span attributes could very well have different order like so:
<div class="col-sm-4">
<span class="::media" id="some-media" >Text</span>
</div>
You got a regex solution, this is a DOMmy one:
var html = `<div class="col-sm-4">
<span id="some-media" class="media">Text</span>
</div>`
var doc = (new DOMParser()).parseFromString(html, "text/html");
var el = doc.getElementsByTagName('span')[0];
el.setAttribute('class', '::' + el.className);
console.log(
doc.getElementsByClassName('::media').length > 0 // check if modification's done
);
Since you have no way except Regular Expressions this can be considered as a workaround:
(<span[^>]*class=.)([^'"]+)
JS:
var html = `<div class="col-sm-4">
<span id="some-media" class="media">Text</span>
</div>
<span class="media" id="some-media">Text</span>
`;
console.log(
html.replace(/(<span[^>]*class=.)([^'"]+)/g, `$1::$2`)
);
This isn't using regex, but you can do it like this in vanilla JavaScript:
const el = document.getElementsByClassName('media')[0];
el.className = '::' + el.className;
Or in jQuery:
const $el = $('div span.media');
$el.attr('class', '::' + $el.attr('class'));
Hope this helps.
Don't parse html with regex, use DocumentFragment (or DOMParser) object instead:
var html_str = '<div class="col-sm-4"><span class="media">Text</span></div>',
df = document.createRange().createContextualFragment(html_str),
span = df.querySelector('span');
span.setAttribute('class', '::' + span.getAttribute('class'));
console.log(df.querySelector('div').outerHTML);
I think this is what you're after:
var test = $("#some-media")[0].outerHTML();
var test2 = '<div id="some-media" class="media">Text</div>'
if(/span/.test(test)) //Valid as contains 'span'
alert(test.replace(/(class=")/g, "$1::"));
if(/span/.test(test2)) //Not valid
alert(test.replace(/(class=")/g, "$1::"));
Since the order differs, writing a regex that captures all possible combinations of syntax might be rather difficult.
So we'd need a full list of rules the span follows so we can identify that span?
Got some more info about if the span occurs in a longer HTML string? Or is the string this span and this span only?
An alternative would be to use one of the several node DOM modules available, so you can work with HTML nodes and be able to use any of the above solutions to make the problem simpler.
But since you're using node:
1) Are you using any templating engines? If so, why not rerender the entire template?
2) Why does the class name have to change on the server side? Isn't there a workaround on the clientside where you do have access to the DOM natively? Or if it's just to add styling, why not add another css file that overwrites the styling of spans with className 'media'?
3) If all of the above is not applicable and it;s a trivial problem like you say, what error di you get using a simple replace?
strHTML.replace( 'class="media"', 'class="::media"' )
or if it has to be regex:
strHTML.replace( /class=\"(.*)\"/, 'class=\"::$1\"' );

paragraph tags in tweet field from web page

I put together a quote machine as an exercise of freecodecamp.com. You click the button, you get a quote. Then, if you want, you can tweet the quote by clicking the "Tweet It" button. I had a lot of trouble figuring out how to get the quote to populate the tweet field. I finally just looked at someone else's code on the issue, and now it is populating.
The problem: it is populating <p> and </p> tags with every quote. Example:
"<p>When typography is on point, words become images.</p>
" Shawn Lukas
It's also annoying that the second set of quotation marks always appears on the line below next to the author's name.
I'm not sure how the tags are getting in there, but I'd like help clearing them out. Here's my code:
HTML
<div id="container">
<div class="content">
<div id="quote" class="triangle-isosceles">
<p>
<span class="msg"></span>
</p>
</div>
<p id="author"><span class="nme"></span></p>
</div>
<button type="button">Get Quote</button>
<a class="twitter-share-button" id="tweet-quote" target="_blank">
<button type="button" class="btn btn-primary">Tweet it!</button>
</a>
</div>
JS
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script>
$.ajaxSetup({
cache: false
});
$('button').on('click', function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content;
var author = a[0].title;
$(".msg").empty().append(quote + "<p>— " + author + "</p>")
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent('"' + quote + '" ' + author));
});
});
</script>
I'm omitting the CSS. I can't get a jsfiddle to work (never can), but here's the CodePen link: https://codepen.io/dtarvin/pen/pePowj
Update: just found a quote with an apostrophe and got back those numbers instead of the symbol. Not sure how to handle that when the quotes are random.
Thanks!
you have "<p>— " + author + "</p>" in the append code, regarding the html entity code you need to parse the quote to switch them to the normal version. Also you might need to remove tags within the a[0].content variable. if you have no control over what is returned, you may need to do a lot more filtering to catch stuff like this.
Or if you have access to the serverside script, then use this to get the quote and return the cleansed quote.
For instance, if you visit the url https://quotesondesign.com/wp-json/posts you will see the <p> tags within the quote themselves.
So you basically need to clean the content of the content variable.
for instance to remvoe the p tag within the content string try:
var quote = a[0].content.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '');
If you need these tags in to display then you could add a seperate function that on pressing the tweet it button, will do this for you.
So you have them on the browser but on tweeting its all striped and good on twitter
Try this it work
<script>
$.ajaxSetup({
cache: false
});
$('button').on('click', function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content;
var author = a[0].title;
$(".msg").empty().append(quote + author);
var html = quote + author;
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent( text ));
});
});
</script>

Insert span in a dom element without overwrite child nodes?

I have an HTML article with some annotations that I retrieve with SPARQL queries. These annotations refer to some text in the document, and I have to highlight this text (wrapping it in a span).
I had already asked how to wrap text in a span, but now I have a more specific problem that I do not know how to solve.
The code I wrote was:
var currentText = $("#"+v[4]["element"]+"").text();
var newText = currentText.substring(0, v[5]["start"]) + "<span class=' annotation' >" + currentText.substring(v[5]["start"], v[6]["end"]) + "</span>" + currentText.substring(v[6]["end"], currentText.length);
$("#"+v[4]["element"]+"").html(newText);
Where:
v[4]["element"] is the id of the parent element of the annotation
v[5]["start"] is the position of the first character of the annotation
v[6]["end"] is the position of the last character of the annoation
Note that start and end don't consider html tags.
In fact my mistake consists in extracting data from the node with the text() method (to be able to go back to the correct position of the annotation) and put back with the html() method; but in this manner if parent node has children nodes, they will be lost and overwritten by simple text.
Example:
having an annotation on '2003'
<p class="metadata-entry" id="k673f4141ea127b">
<span class="generated" id="bcf5791f3bcca26">Publication date (<span class="data" id="caa7b9266191929">collection</span>): </span>
2003
</p>
It becomes:
<p class="metadata-entry" id="k673f4141ea127b">
Publication date (collection):
<span class="annotation">2003</span>
</p>
I think I should work with nodes instead of simply extract and rewrite the content, but I don't know how to identify the exact point where to insert the annotation without considering html tags and without eliminating child elements.
I read something about the jQuery .contents() method, but I didn't figure out how to use it in my code.
Can anyone help me with this issue? Thank you
EDIT: Added php code to extract body of the page.
function get_doc_body(){
if (isset ($_GET ["doc_url"])) {
$doc_url = $_GET ["doc_url"];
$doc_name = $_GET ["doc_name"];
$doc = new DOMDocument;
$mock_doc = new DOMDocument;
$doc->loadHTML(file_get_contents($doc_url.'/'.$doc_name));
$doc_body = $doc->getElementsByTagName('body')->item(0);
foreach ($doc_body->childNodes as $child){
$mock_doc->appendChild($mock_doc->importNode($child, true));
}
$doc_html = $mock_doc->saveHTML();
$doc_html = str_replace ('src="images','src="'.$doc_url.'/images',$doc_html);
echo($doc_html);
}
}
Instead of doing all these, you can either use $(el).append() or $(el).prepend() for inserting the <span> tag!
$("#k673f4141ea127b").append('<span class="annotation">2003</span>');
Or, If I understand correctly, you wanna wrap the final 2003 with a span.annotation right? If that's the case, you can do:
$("#k673f4141ea127b").contents().eq(1).wrap('<span class="annotation" />');
Fiddle:
$(document).ready(function() {
$("#k673f4141ea127b").contents().eq(1).wrap('<span class="annotation" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="metadata-entry" id="k673f4141ea127b">
<span class="generated" id="bcf5791f3bcca26">Publication date (<span class="data" id="caa7b9266191929">collection</span>): </span>
2003
</p>
At the end my solution is in this Fiddle.
Generalizing:
var element = document.getElementById(id);
var totalText = element.textContent;
var toFindText = totalText.substring(start,end);
var toReplaceText = "<span class='annotation'>"+toFindText+"</span>";
element.innerHTML = element.innerHTML.replace(toFindText, toReplaceText);
Hope it could help someone else.
Note: This don't check if two or more annotations refers to the same node, I'm working on it right now.

Javascript delete div text from string

I have a string which contains 2 div in it with their text and settings.
for example :
<div class="a" id="b">blabla </div><div class="a">Here is the text i need to get </div>
I need to pull out the text from this string, cant use sub string cause the text is dynamic and not always written the same.
Thanks
var str = '<div class="a" id="b">blabla </div><div class="a">Here is the text i need to get </div>';
var tmp = document.createElement('div');
tmp.innerHTML = str;
console.log(tmp.innerText || tmp.textContent); // is this what you want?
Try a regex replace like
'<div class="a" id="b">blabla </div><div class="a">Here is the text i need to get </div>'.replace(/(\<div.*?\>|\<\/div\>)/g, '')
Demo: Fiddle

Categories

Resources