Formatting numbers in a td - javascript

My code gets some totals that look like this:
var totals = { someInt:5, someFloat:7.555, someNumberIDoNotNeed:7};
I'd like to present a subset of these in a table in a view (via a jade template). My idea was to put the ones I want into an object, then let JSON.stringify do the formatting for me. I wanted one of the values to be rendered boldface:
var needed = {};
needed["The int is"] = parseFloat(totals.someInt);
needed["The float is"] = "<b>" + parseFloat(totals.someFloat).toFixed(2).toString() + "</b>";
// get rid of the curly braces and add a space after the commas
var string = JSON.stringify(needed).replace(/[{}"]/gi, '').replace(/,/gi, ', ');
Then in my jade view:
td= string
Reviewing this in the Chrome inspector, the string seems to be what I hoped for:
<td>
"The int is:5, The float is:<b>7.55</b>"
</td>
But the browser isn't respecting the markup. I just see the braces and b (< b >) in the output. I've tried a few variants in formatting the output, but the basic problem of the marking showing remains the same. Would appreciate any pointers in the right direction.
(I tried to quote the output using SO's > quote formatting, but it actually respects the in my markup, and this question shows up with the bold output just how I want it. Somehow SO gets this right but I cannot!)

I've never heard of Jade before, but I took a quick look at their editable demos and reference and noticed that td= string syntax escapes html entities but td != string does not.
So that seems to be your problem. You want to keep the html intact in this case. So give td != string a try.

Related

Building HTML as String with Variables in Javascript

I'm trying to declare a string in javascript that will consist of HTML and a javascript var to declare the ID.
My problem is that I keep seeing "The server tag is not well formed" OR "Is not a valid identifier"
I believe this has something to do with the string/quotation configuration but I can't seem to find a clear answer.
My Problem
var HTMLStr, newtbl = tbl + "Table";
HTMLStr = '<tbody id="' + newtbl + '" class="prodTbl" runat="server"><tr>';
This produces the following error:
Parser Error: '' + newtbl + '' is not a valid identifier.
I see that in the error it changes the quotations and I've tried switching the quotations multiple times between double and single quotes but nothing seems to be working.
Can anyone provide some insight as to how I might be able to write this HTML string and declare the ID with a javascript variable??
Thanks again for all your help!
________________________________Comment Answers/Edit________________________
Kolt Penny: So I am planning on assigning the string to a var which will then be assigned back to the DOM like such
$('#DOMName').html(HTMLStr);
I also tried changing the
SvenWritesCode: The value of table in this instance is the string "Salad" which was passed to the function.
Also I did change the string to the indicated
(I am using asp.net as well this string would essentially be injected as a new table row in an asp.net table and will consist of a newly constructed table itself, resulting in the following)
asp:table
asp:tablerow
asp:tablecell /
/asp:tablerow
asp:tablerow
asp:tablecell
{HTML Table injection Point}
/asp:tablecell
/asp:tablerow
/asp:table

How to add single quote "'" to javascript string

So many related questions out there, but none satisfyingly answered using javascript (no jQuery).
I wish to add quotes around a variable in a string I'm building. My string itself should contain single quotes within it like so:
'{'a'}'
I can get:
'{a}'
When I try to add single quotes around the key a I get:
'{\'a\'}'
I've used both of the following syntax with the same result.
Any suggestions??
concat('\'','a','\'')
'\''+'a'+'\''
See line 39 of this code: https://repl.it/#mike_butak/LiveForHisPleasureHeReallyIsThere
Thanks!
Like this?
console.log("'{'a'}'")
To expand on this, when you are building the string, just use " around the string, and ' within the string.
Having a hard time replicating your issue! See:
var temp = '\'{\'a\'}\'';
console.log('s' + temp + 's');
I'd definitely recommend demonstrating the issue you are asking about in a console print or in a readily available editor online before posting a question!
As per your comment, updating to make it part of a variable assignment. Still unclear what the issue is!

Prevent Table Cell to Convert HTML Entities

<table>
<tr>
<td>></td>
</tr>
<tr>
<td>&GT</td>
</tr>
</table>
I have the above code for table cells having html entities. Also, I have a related question (which is now answered) having the same details but with different scenario.
The goal is to output the string as is, without converting it to HTML Entities. For example the string "Project &GT" will be outputted as is.
Below are 2 solutions I've tried but still does not meet my requirements (these are answers from question)
A. First Row - this answer does not correctly display the string. It displays the converted html which is ">". But this solution works on non-table elements like tooltips and spans. Also, if the string has different casing (Project&gT) it outputs the casing from the original string.
B. Second Row - this answer do display the string correctly. It does not output the converted string. But my problem here is if the string has different casing (Project&gT) it will output the case you have encoded on the logic (Project&GT - since this is the one we encoded on the HTML).
Is there a way to have an unconverted string and preserve its casing?
UPDATE: Forgot to mention that I am using this with angular.datatable's renderWidth.
.renderWith(function(data) {
return $filter('customFilter')(data)});
I've used it together with a customFilter to stop the conversion. In my debugging, the filter returns the correct result but it always has a problem when it renders to table cells . This is why I directly asked the question about prior to this update
If you use angular, use ng-bind it's alwais give you the plain text.
Hire is the link
To get &gt ; use ng-bind
to get > use ng-bind-html
Try it.
You could do something like this:
function findNoParse(){
$('noparse').each(function(){
if($(this).attr('tagchecked') != 'true'){ //checks if already changed tag
$(this).text($(this).html()); //makes the html into plaintext
$(this).attr('tagchecked', 'true'); //says that tag has been checked
}
});
}
In HTML
<noparse>Link</noparse>
I have created a fiddle. Please take a look. Fiddle

Javascript - search for HTML elements in string

I have string with html elements. There are tables with captions. I need to find table which has caption with certain text and then return this table - as a string.
What is the best way to do this with simple javascript, without any libraries ?
F.e. this is an initial string
<table border="1"><caption><strong>First</strong></caption><tbody><tr><td>...</td></tr></tbody></table><table border="1"><caption><strong>Result</strong></caption><tbody><tr><td>...</td></tr></tbody></table><table border="1"><caption><strong>Last</strong></caption><tbody><tr><td>...</td></tr></tbody></table>
I want to get this string :
<table border="1"><caption><strong>Result</strong></caption><tbody><tr><td></td></tr></tbody></table>
Any advice or algorithm how to effeciently resolve this problem ? The challenge is to resolve it with javascript without using any third-party libraries and also without converting text into xml or something similar (because some of html code is not well formatted and it causes errors).
I have not had time to completely test this, but you might be able to try using a regular expression and the match() function. Assuming your table string is in a variable called str, then something along the lines of
var res = str.match(\b<table\.\w+_</table>\b);
res will be an array of matches of strings that begin with '', which you could then check to see which string contains the caption that you need.
Hope that helps!

Javascript "Replace" not working on string returned via jQuery

I'm trying to convert a currency string to a number. I'm using a replace function with a regexp that I've used successfully in a similar context before.
The currency string is captured here, in part of an "each" loop:
var unitGridPrice = jQuery(this).find(".clsPriceGridDtlPrice").html();
The result is that unitGridPrice is a currency string, something like "$2.75". I'm trying to convert it to a number here:
var priceToConvert = unitGridPrice;
var unitGridPriceNo = Number(priceToConvert.replace(/[^0-9\.]+/g, ''));
However with that last line in place, the script will not run.
If I use the value of priceToConvert it correctly displays the currency text string, so I believe the string feeding the replace function is correct.
if I change "var priceToConvert = unitGridPrice" to "var priceToConvert = "$2.75" the script properly returns 2.75. I can copy and past the value that unitGridPrice displays into the text string I'm testing with and it works, but with the variable there the script dies.
I've tried removing the regex, changing the replace to .replace('$', '') and again the script stops with the variable in place but works if I test with a fixed string.
I'm really stumped. Help??!! Thank you!!!
i had some problem while try to get number from string also, little time ago. the problem is the regex, so i changed the regex like code below.
var id = element.name.replace ( /[^\d.]/g, '' );
element.name above is like input_21,input_22, etc. and i wanna get only the number(21,22).
hope it can help you. :)

Categories