filter incoming text from api jade - javascript

My system relies on fetching data from an API and then inserting the data into the jade template how ever one field is fetched with unirest and passed into jade like so
unirest.get('apiurl.com/endpoint')
.header('API-KEY', 'val1')
.header('Accept', 'text/plain')
.end(function(result) {
res.render('home', {
title: "Home",
obj: result.body.target
}
}
then calling obj in the view like so
p
#{obj}
which returns the text fromt the API however it returns it enclosed in brackets (<>)
my aim is to remove the < and > tags and keep the text inside

UPDATE: I Fixed this by calling the variable using this line
p #{obj}

What you want is this:
p= obj
As you found out, p #{obj} works too. That's Jade's string interpolation syntax, which is useful when you want to put a variable in the middle of some other text (e.g. h1 Hello #{name}!), but when all you want inside the tag is the value of the variable, you should use = instead. See the documentation for buffered code.

Related

JS parse object wrapped in a string using same quotes as object keys

Consider the following event payload data returned via WS:
{
id: "1",
foo: "{"bar":"baz"}"
}
The current output of JSON.stringify(event.foo):
"{\"bar\":\"baz\"}"
Also consider the backend have no real way to return the foo value formatted differently and I need to find a way to parse the string associated to this foo key in order to access it's value of bar.
The identified problem is the fact that the quotes used to wrap the whole supposed object are the sames used in the object itself, resulting in making JSON.parse() impossible.
I'm wondering if there is a "clean" way to achieve this.
So far, I tried:
using JSON.parse() which fails due to the format of the string raising Unexpected end of JSON input
trimming external quotes and converting inner ones to single then parsing, results in same error.
using new Object(...) based on the string (trimmed of external quotes)
replacing all quotes with single ones and wrapping it again in double ones to parse it.
Any input appreciated
The problem here is the backend should really be fixed, but some reason you can not do it. Next issue is you can "fix it" on the front end, but you are putting a band aid on the problem and it will fall off when the data that comes back is not what you expect. So the solutions will be error prone unless you know the data coming back will be a specific type.
With this said, you can fix the invalid JSON that you have in your simple example with a couple of regular expressions. Problem is, if your data contains characters such as } in the text, this is going to fail.
var response = `
{
id: "1",
foo: "{"bar":"baz"}",
goo: "{"gar":"gaz"}"
}
`
var reObj = /"(\{[^}]*})"/
while (response.match(reObj)) {
response = response.replace(reObj, '$1')
}
var reKey = /^\s+(\S+):/m
while (response.match(reKey)) {
response = response.replace(reKey,'"$1":')
}
var obj = JSON.parse(response)
console.log(obj)

Angular 2 - Display variable inside a variable in a template

I'm quite new in Angular 2, and I want to show in my template a string in a variable that has to contain inside another variable. I will show you a simplified example of what my problem is and what I want to achieve:
questionnaire.component.ts
/* Starts being "", populating an input text will modify this */
name = "Albert";
/* This variable comes from calling an API, here I just put it as created to simplify */
question.title = "Hello {{name}}, how old are you?";
questionnaire.template.html
<p>{{question.title}}</p>
The result I'm getting is:
Hello {{name}}, how old are you?
and my desired result would be:
Hello Albert, how old are you?
I have tried to escape the "{{ }}" in the string stored on my DB, used the ASCII character instead of the curly braces, put it inside [innerHTML]... but the result was always the same.
Do you know how can I solve this?
Thank you very much!
{{}} only works in Angular component templates and not in arbitrary strings and also not in HTML added dynamically to the DOM.
Just change it to
question.title = `Hello ${this.name}, how old are you?`;
to use TypeScript string interpolation.
In angular2 you have to use this keyword
For example, ${this.name}

Unable to remove html tags from response JSON

Hi I am new to AngularJS. I am having a problem parsing JSON data to proper format. Actually the JSON response itself returned HTML format data (it contains HTML tags like &lt,;BR,> etc). If I check the response in browser it returns fine, but in device(TAB,MOBILE) the HTML tags are also getting appended. I am using AngularJS to bind the JSON response to DOM. Is there any way to simply ignore HTML tags in JQuery or in AngularJs? At the same time I don't want to remove the HTML tags as they are necessary to define "new line", "space", "table tag" etc.
A sample response I am getting is like:
A heavier weight, stretchy, wrinkle resistant fabric.<BR><BR>Fabric Content:<BR>100% Polyester<BR><BR>Wash Care:<BR>
If I apply the binding using {{pdp.desc}}, the HTML tags are also getting added. Is there any way to accomplish this?
I have added ng-bind-html-unsafe="pdp.desc", but still "BR" tags r coming.
useless html tags can be remove using regix expression, try this
str.replace(/<\/?[^>]+>/gi, '')
Try to use three pairs of brackets {{{pdp.desc}}} In Handlebars it works, possible in your case to.
Use JS HTML parser
var pattern = #"<(img|a)[^>]*>(?<content>[^<]*)<";
var regex = new Regex(pattern);
var m = regex.Match(sSummary);
if ( m.Success ) {
sResult = m.Groups["content"].Value;
courtesy stackoverflow.

jQuery replacing spans in node+jade combo

Perhaps this is expected, but I found it odd since I am now starting with jQuery.
So, I am writing an application using node and jade. In the index.jade I have a statement of the form
p Welcome subscriber
span(id="subscriber") someID
Now once the connection is established between the client and the server, the server sends a welcome JSON message with some data. One of them is the id of the client which I want to replace above. Once the client receives the welcome JSON message it initializes the appropriate structures and then I make a call to a function loadStats:
function loadStats() {
var myText = "" + myData.id + ".";
$('#subscriber').text(myText);
$('#subscriber').html(myText);
};
In the screen I can see that the text "someID" is replaced by the ID of the client. However, when I actually inspect the html code of the page that I am looking at I see a statement of the form:
<p>Welcome subscriber <span id="subscriber">someID</span></p>
In other words in the actual HTML code the text "someID" has not been replaced. Is this something expected? How was the replacement done? Moreover, it appears that working with either of the statements
$('#subscriber').text(myText);
$('#subscriber').html(myText);
gives the replication on the screen but not on the actual html content of what is presented on screen. Is this the correct behavior? From what I understood (and expect) the .text() replaces the visual data of the element with the specific id and the .html() replaces the content. Am I missing something?
Thanks in advance. jQuery rookie here.
Two rules for expressions in pug:
In attributes you use quotes to output literal text and you leave the quotes out when you want to use a variable, and
For the content of a tag you use an equals sign when you want pug to evaluate an expression, or don't put anything if you want literal text
So with those rules in mind, looking at your code you will output the attribute "subscriber" as a literal and "someId" as a literal.
span(id="subscriber") someID
Results in:
<span id="subscriber">someId</span>
You wanted both to be dynamic so remove the quotes in the attribute and put an equals sign after the element:
span(id= subscriber)= someID
This will dynamically replace both with variables.

Does something similar to gsub exist in javascript?

Is there any way to to do something similar to ruby gsub in javascript? I have a local html file that I want to process and replace certain template variables with content but I cannot figure out how to substitute out the template variables with the new content. The html contains fragments like below:
<div id="content">
<h1>{{title}}</h1>
{{content}}
</div>
Now if I wrap every template variables in a named div then I can use something like jquery's replaceAll method to replace the template variable with its content but I cant figure out how to do it without wrapping every variable in a div.
I just want to do something like $('document').gsub("{{title}}", "I am a title").
Anyone have any ideas?
Thanks for your help!
If others were looking for an equivalent to gsub in general, this only replaces the first match:
"aa".replace("a", "b") // "ba"
//g replaces all matches:
"aa".replace(/a/g, "b") // "bb"
"aa".replace(new RegExp("a", "g"), "b"); // "bb"
You can access the raw HTML via a DOM element's innerHTML property, or using JQuery's html property wrapping it, and then perform the substitution:
var html = $(document).html();
$(document).html(html.replace('{{title}}', 'I am a title');
EDIT:
As pointed out by Antti Haapala, replacing the entire document HTML can have side-effects you don't want to deal with, like scripts being reloaded. Thus, you should drill down to the most specific DOM element possible before performing the substitution, i.e.:
var element = $('#content');
var html = element.html();
element.html(html.replace('{{title}}', 'I am a title');
Well, you can use String.replace with a regex, but really, what you could use are jQuery Templates.
http://api.jquery.com/category/plugins/templates/
I recently used Handlebars to take a data attribute (template) from a table and inject another value (record id) from one of its rows:
// data-row-url="http://example.com/people/{{id}}"
var table = $(this).closest('.data_grid table');
if(table.attr('data-row-url')) {
var record_id = $(this).data('record-id')
var show_url_template = table.data('row-url');
var url_template = Handlebars.compile(show_url_template)
var url = url_template({ id: record_id });
$.getScript(url);
}
For context this code runs from inside an onclick event for the table's tr elements and fetches the clicked record via ajax.
I believe that might be a mustache template. You might want to check mustache.js. I think you might be able to compile that to JS.

Categories