Unterminated string constant during #Html.Partial from javascript object - javascript

var html = '#Html.Partial("_mypartialview")';
$("#container").html(html);
I am working in a single page application and I don't want to hide the container div element; instead I want to load the html content into my javascript object.
But I get the error:
Unterminated string constant.
I have tried various methods without any success. Any help as to why I get this error would be really appreciated.

Like this
var html = "#Html.Partial("_mypartialview").ToHtmlString().Replace("\n", "<br/>").Replace(" ", "")";
The ToHtmlString() method HTML encodes your html so the quotes won't confuse your JavaScript.
The two replace methods will remove new lines and whitespace so the content is all on one line.
Update
_mypartialview
<div>
<span data-bind="text:playerInfo.Name"> </span>
</div>
Code
var html = "#Html.Partial("_mypartialview").ToString().Replace(Environment.NewLine, "").Replace(" ", "")"
This outputs the following
var html = "<div><spandata-bind="text:playerInfo.Name"></span></div>"

Related

Convert String from Element to working HTML code with jQuery

I'm having a checkbox which is generated dinamically. The Checkbox text contains a string with some html code inside of it. The text comes directly from the database and doesn't display it as html, but just as a string. Is it possible to convert the string to html, so it get displayed correctly? The checkbox:
<label for="id_122_gen">"I hereby consent to the processing of my above-mentioned data according
to the <a href="/declarationofconsent.pdf" target="_blank">declaration of consent." </label>
<input type="checkbox" name="confirm" id="id_122_gen" >
I tried to get the containing text with $.text() method, what worked so far.
$mystring = $("#id_122_gen").text();
After that I've tried to use jQuery method $.parseHTML() and save the result again.
$myhtml = $.parseHTML( $mystring );
Apparantly it is saved as an array, because when I try to save the result again with the $.text() method, it displays:
[object Text],/declarationofconsent.pdf,[object Text]
It's just this. No clickable link and the checkbox disappeared aswell. I'm a bit confused now what to do and don't know how I can display the correct content with a clickable link.
The solution depends on how the html of your page is generated. Your label either has has it's inner html escaped or not.
This is important; inspect view may guide you wrong with escaped HTML and show as proper HTML, so make sure to check the page source.
Most likely your data is HTML escaped and that's why you can't see the link on initial render.
If you see < and > inside the label's source it's HTML escaped.
If it's escaped and you just want to convert it to proper HTML and set it to the label, use this:
$("label[for='id_122_gen']").html( $("label[for='id_122_gen']").text() );
Basically this unescapes the label's value. It reads the innerHTML as text and thus changes the escaped characters to real ones, and when you set it back as it's html value and the innerHTML becomes unescaped.
If you just want to get the link, read on.
If the value inside the label is HTML escaped then you'll have to use .text() to read that value. If it contains unescaped HTML then you'll have to use .html().
Afterwards the flow is the same, you parse the html first.
Since there is text and a link, the parsed html will return as an array with multiple elements. If you just want to get the link you have to search in the array.
You can check out the code below.
$mystring = $("label[for='id_122_gen']").text(); //Use .html() for unescaped
$myhtml = $.parseHTML( $mystring );
var mylink = null;
var e;
while (e = $myhtml.pop())
{
if(e.tagName == "A"){
mylink = e;
break;
}
}
console.log(mylink);

Get HTML attribute value as is via JavaScript

I have a website where I feed information to an analytics engine via the meta tag as such:
<meta property="analytics-track" content="Hey There!">
I am trying to write a JavaScript script (no libraries) to access the content section and retrieve the information as is. In essence, it should include the HTML entity and not transform/strip it.
The reason is that I am using PhantomJS to examine which pages have HTML entities in the meta data and remove them as they screw up my analytics data (For example, I'll have entries that include both Hey There! and Hey There! when in fact they are both the same page, and thus should not have two separate data points).
The most simple JS format I have is this:
document.getElementsByTagName('meta')[4].getAttribute("content")
And when I examined it in on console, it returns the text in the following format:
"Hey There!"
What I would like it to return is:
"Hey There!"
How can I ensure that the data returned will keep the HTML entity. If that's not possible, is there a way to detect HTML entity via JavaScript. I tried:
document.getElementsByTagName('meta')[4].getAttribute("content").includes(' ')
But it returns false
Use queryselector to select the element with the property value "analytics-track", outerHTML to get the element as a String and match to select the unparsed value of the content property with Regex.
document.querySelector('[property=analytics-track]').outerHTML.match(/content="(.*)"/)[1];
See http://jsfiddle.net/sjmcpherso/mz63fnjg/
You can't, that isn't really there. Its just an encoding for a non-breaking space. To the document, the DOM, the web page, to everything, it looks like:
Hey There!
Except the character between the y and the T isn't a space of the sort you'd get by hitting the space bar, its a completely different character.
Observe:
<span id='a' data-a='Hey There!'></span>
<span id='a1' data-a='Hey There!'></span>
<span id='b' data-b='Hey There!'></span>
var a = document.getElementById('a').getAttribute('data-a')
var a1 = document.getElementById('a1').getAttribute('data-a')
var b = document.getElementById('b').getAttribute('data-b')
console.log(a,b,a==b)
console.log(a,a1,a==a1)
Gives:
Hey There! Hey There! false
Hey There! Hey There! true
Instead, consider altering your method of 'equality' to view a space and a non-breaking space as equal:
var re = '/(\xC2\xA0/| )';
x = x.replace(re, ' ');
To get the HTML of the meta tag as is, use outerHTML:
document.getElementsByTagName('meta')[4].outerHTML
Working Snippet:
console.log(document.getElementsByTagName('meta')[0].outerHTML);
<meta property="analytics-track" content="Hey There!">
<h3>Check your console</h3>
Element.outerHTML - Web APIs | MDN
Update 1:
To filter out the meta content, use the following:
metaInfo.match(/content="(.*)">/)[1]; // assuming that content attribute is always at the end of the meta tag
Working Snippet:
var metaInfo = document.getElementsByTagName('meta')[0].outerHTML;
console.log(metaInfo);
console.log('Meta Content = ' + metaInfo.match(/content="(.*)">/)[1]);
<meta property="analytics-track" content="Hey There!">
<h3>Check your console</h3>

MVC with Razor: assigning html text

I am trying to assign to a javascript variable some html script, but cannot succeed. Here is what I am trying:
var blah = #Html.Raw("Some <strong>text<\/strong>");
I cannot even say what the error is, as the result I get looks cryptic:
Thanks
Html.Raw is used to keep a fragment of html from being encoded and displayed as plain text. You're not using it with actual html, you're using escaped text. try adding single quotes inside the double quotes:
<script>
var plork = #Html.Raw("'Some <strong>text</strong>'");
alert(plork);
</script>
OR
putting the Html.Raw inside single quotes:
<script>
var plork = '#Html.Raw("Some <strong>text</strong>")';
alert(plork);
</script>
instead

removing html tags from string

I am trying to remove the HTML tags from a string. Right now I am able to remove the complete HTML tags like for example <div class="test">dadsasdsad</div> gives me the output dadsasdsad.
But I'm unable to remove partial tags like class="test">dadsasdsad</div> or testing<div class=
The regular expression that Ive used is
strippedText[i] = fragments[i]
.replace(/<(?:.|\n)*?>/gm, '')
.replace(replaceAT, '<span style=font-weight:800>')
.replace(replaceET, '</span>');
Here fragments[i] contains the input <div class="test">dadsasdsad</div>;
strippedText[i] = fragments[i]
// full tags
.replace(/<[^>]+>/gm, '')
// partial tags
.replace(/^[^>]+>/gm, '')
.replace(/<[^>]+$/gm, '');
Note that ^ has different meanings: "not" within brackets, "start" outside brackets.
/gm should not be necessary for partial tags, but I left them as I don't know your context and how you're getting partial tags.
my simple JavaScript library has a function called "strip_tags()" which does the long work for you.
Just say that you have a sentence loaded with HTML formatting tags, and you want to remove them, simply do it like this:
strip_tags("<p>This <em>sentence</em> contains <strong>a lot</strong> of tags!</p>");
This will output "This sentence contains a lot of tags!" (tested on the documentation website).
To read more about this function, please read the documentation at http://docs.funcjs.webege.com/strip_tags().html and if possible, leave feedback through the Feedback Form on the website.
Hope this helps you and anyone else with the same problem! :)
Using javascript you can do this:
function removeHTMLTags(htmlString) {
if(!htmlString) { return; }
var mydiv = document.createElement("div");
mydiv.innerHTML = htmlString;
return mydiv.textContent || mydiv.innerText || '';
}
[Source]

Find Html Inside a String Using Jquery

I am not sure how practical this question is , but what i am trying to do is find html inside a string and then append pre tags to it using jquery. let say i have a variable with following string.
var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
Html inside the string is dynamic and can contain any tags , what i want is to find the starting and ending of html and append,prepend pre tags accordingly.
Thanks
The following code does pretty much what you want, however it does not allow html, body tags etc. But those are not allowed in pre tags anyway.
var string = "Some normal text <html><body><div> This is the html </div> </body></html> more text<p>more html content</p>";
var holder = $('<div>').html(string);
holder.children().wrap('<pre>');
//Print result to console
console.log(holder.html());
Also a jsFiddle here: http://jsfiddle.net/evBCm/1/
Add the text to dynamic html tag e.g span or div and find desired node e.g
var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
$("<span/>").html(string).find('div')
Apply bellow regix..
var string = "Some normal text <html><body><div> This is the html </div> </body></html>";
var iMatches = string.match("<html>(.*)</html>");
var iHtml='<html>'+iMatches[1]+'</html>';
alert(iHtml);

Categories

Resources