htmlparser2 convert xml object into string - javascript

I'm having a little trouble getting the htmlparser2 module (using node.js) to output an xml string. Basically I'm parsing it in like so:
var htmlparser=require('htmlparser2');
function(xmlString,cb){
var handler=new htmlparser.DomHandler(cb);
var parser = new htmlparser.Parser(handler);
parser.write(xmlString);
parser.done();
}
Then I get an object called "dom", which I do some work on. After that work is done, I want to export it back into an XML string. I know that htmlparser.DomUtils.getOuterHTML(dom) works for HTML objects, but doesn't work for XML (at least not by default). I get back <undefined></undefined> when I call htmlparser.DomUtils.getOuterHTML(dom) on an xml dom.
Thanks in advance for any help you're able to offer!
-Dylan

Fixed. Basically you need to use a second option in getOuterHTML...
htmlparser.DomUtils.getOuterHTML(dom,{xmlMode:true})
If that doesn't work, try calling on the inner elems in the array like:
htmlparser.DomUtils.getOuterHTML(dom[0],{xmlMode:true})
You'll have to wrap a for loop around it to get the whole document, but it works for me!

Related

I am trying to convert some vanilla JavaScript into jQuery. But all I every get returned is [object object]

I am creating a chatbot. In this function on my js page I am putting the users response into its own 'div' container and adding a time-stamp underneath it. I do it like this so that I can easily access the CSS selectors. All of this code was previously only vanilla JavaScript and worked wonderfully. After having converted it over to jQuery all I get displayed is [object Object]. I am extremely new to jQuery, so a lot of these concepts may have gone over head. Please help me out.
function addChatToChatBoxUser(userReply){
const $chatBox =$("#messages")[0];
var $timestamp2 = $("<div>").addClass("timestamp2");
timestamp2.html(`${new Date()
.toString()
.split(" ")
.slice(0,5)
.join(" "));
var $repliesContainer = $("<div>").addClass("chat-user-side").attr("id", 'userMessages');
var $userDiv = $("<div>").addClass("guest response").attr("id", 'guest');
userDiv.html(`${inputReply}`);
$repliesContainer.append($userDiv);
$repliesContainer.append($timestamp2);
$chatBox.append($repliesContainer);
$chatBox.scrollTop = $chatBox.scrollHeight - $chatBox.clientHeight;
}
The problem is that const $chatBox =$("#messages")[0]; will return the DOM node, and not the jQuery object.
So when you later do $chatBox.append($repliesContainer); it will use the .append of the actual node which will try to convert the $repliesContainer to a string (since it is not a node).
Use $($chatBox).append($repliesContainer); for the correct jQuery .append
man sorry but is ur chatbot using vanilla js having like a array based one like one folder with all functions to import and another with the const for q and const for a
... pls respond cause i also need some help cause i also made one using vanilla and im a complete newbie to progarming as a whole....

JQuery String Concatenation within a String

I'd like to preface this by saying I'm new to JQuery and this may be a simple question, but I was unable to find a solution after searching to the best of my ability.
I am trying to build a path to an image, where I am working with an API which returns an object that gives part of the path but not the base path.
Ex:
Base path = Youtube.com/watch/?
Path piece from API: /gdsrhab
On line 29 you can see I am trying to perform string concatenation within trying to build the "results" string. I understand why this is not working the way I've set it up, but am not sure how to syntactically perform this (if possible).
I've also tried to create two variables: baseURL and apiURL, concatenate them and save the result into completeURL then substitute it in, but it JQuery takes the string literal "completeURL" instead of substituting the value of the variable. Could someone point me in the right direction for how to get the full path within the tag? Thanks in advance for your help.
Picture of my JQuery code
In the following picture you can see the second half of the path is missing
The error message I receive
You are using ES6 string templates at start, so you only need to set your variable inside the ${}, you dont need to concate it, the string template will do it for you. So instead of
<img src = 'http...../' + '${movie.poster_path}'}>
that will output something like:
<img src="'http://yoururl.com/'+'mypath'"
you only need to do
<img src = 'http://yoururl.com/${movie.poster_path}'>
inside your string template

convert string to json and than read the json value

First of all, I'm fairly new to json, so please forgive me if I've made a terrible mistake. I've got some code that gets a json object from a website using YQL It returns it as a string. So now I want to parse this into a json object and than read it.
This is my code:
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url=%22http://iphone-api.uitzendinggemist.nl/v1/episodes.json%22%20and%20xpath=%27*%27&format=json", function(data) {
console.log(data);
content = data.query.results.html.body.p;
json = JSON.stringify(eval("(" + content + ")"));
str = json.revoked;
$('#table').append('<li>' + str + '</li>');
});
JS fiddle
I just can't figure out why this gives me undifined, instead of the value it should give.
So now my question was if someone here knows why it isn't working properly.
The json variable is an array, you need to access an index.
string = json[0].revoked;
You have many many many errors in your code. You should try to understand each step that you are doing, it looks like you don't. Here's a fork of your code that does something, I'm not sure what you want it to do. I'll tell you few things you did wrong:
Use var keyword when declaring new variables within functions
Don't parse JSON using eval(), but use some parser. E.g. $.parseJSON(). Using eval() is a security risk, as returned script WILL be executed on client and you should only be interested in getting data.
When constructing HTML, take care to encode text that you want displayed. In your case, don't concatenate strings ('<li>' + str + '</li>'). You can use jQuery ($('<li>').text(str)).
Don't add li elements to a table element. Either add them to ul or ol elements, or in case of tables create rows and cells.
It is completely unclear why you would eval, and them stringify an object. You end up with same exact data.

Create 2d array from string

I have the following string :
[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],]
How can I create a 2d array of strings from it ?
EDIT
I've removed html tags since they're not the problem here. Also I'd like to do it without using any additional libs to keep it lightweight.
Except from the HTML tags in it, it would be valid JSON. You could remove the HTML tags and parse it using any library that handles JSON, like jQuery:
var arr = $.parseJSON(theString.replace(/<br\/>/g,''));
It would also be valid Javascript code with the HTML tags removed, so if you have full control over where the string comes from so that you are certain that it can never contain any harmful code, you could use the eval function to execute the string:
// Warning: 'eval' is subject to code injection vulnerabilities
var arr = eval(theString.replace(/<br\/>/g,''));
You will need to remove the <br/> from the string. Then you should be able to do:
var my2darray = eval(mystring);

Is it possible to get jquery objects from an html string thats not in the DOM?

For example in javascript code running on the page we have something like:
var data = '<html>\n <body>\n I want this text ...\n </body>\n</html>';
I'd like to use and at least know if its possible to get the text in the body of that html string without throwing the whole html string into the DOM and selecting from there.
First, it's a string:
var arbitrary = '<html><body>\nSomething<p>This</p>...</body></html>';
Now jQuery turns it into an unattached DOM fragment, applying its internal .clean() method to strip away things like the extra <html>, <body>, etc.
var $frag = $( arbitrary );
You can manipulate this with jQuery functions, even if it's still a fragment:
alert( $frag.filter('p').get() ); // says "<p>This</p>"
Or of course just get the text content as in your question:
alert( $frag.text() ); // includes "This" in my contrived example
// along with line breaks and other text, etc
You can also later attach the fragment to the DOM:
$('div#something_real').append( $frag );
Where possible, it's often a good strategy to do complicated manipulation on fragments while they're unattached, and then slip them into the "real" page when you're done.
The correct answer to this question, in this exact phrasing, is NO.
If you write something like var a = $("<div>test</div>"), jQuery will add that div to the DOM, and then construct a jQuery object around it.
If you want to do without bothering the DOM, you will have to parse it yourself. Regular expressions are your friend.
It would be easiest, I think, to put that into the DOM and get it from there, then remove it from the DOM again.
Jquery itself is full of tricks like this. It's adding all sorts off stuff into the DOM all the time, including when you build something using $('<p>some html</p>'). So if you went down that road you'd still effectively be placing stuff into the DOM then removing it again, temporarily, except that it'd be Jquery doing it.
John Resig (jQuery author) created a pure JS HTML parser that you might find useful. An example from that page:
var dom = HTMLtoDOM("<p>Data: <input disabled>");
dom.getElementsByTagName("body").length == 1
dom.getElementsByTagName("p").length == 1
Buuuut... This question contains a constraint that I think you need to be more critical of. Rather than working around a hard-coded HTML string in a JS variable, can you not reconsider why it's that way in the first place? WHAT is that hard-coded string used for?
If it's just sitting there in the script, re-write it as a proper object.
If it's the response from an AJAX call, there is a perfectly good jQuery AJAX API already there. (Added: although jQuery just returns it as a string without any ability to parse it, so I guess you're back to square one there.)
Before throwing it in the DOM that is just a plain string.
You can sure use REGEX.

Categories