So I have a string like this
string = "<user>username 1<notes>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>"
How could I parse the string in Javascript or JQuery to pull out the "Notes" of either user 1 or user 2.
So I'll have a variable like this:
variable = user;
printout notes of user.
You mean an XML like string, not a HTML like string. jQuery has a lovely XML parser for that http://api.jquery.com/jQuery.parseXML/
to identify the notes of user1 or user2 you need to change your xml a bit
string = "<user>username 1<notes id='user1'>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>"
notice that i added id=user1
alert($(string).find("notes[id='user1']").text());
here is the fiddle http://jsfiddle.net/Qa5sP/
EDIT after the -1 :(
No, jQuery selectors do not parse XML.
This may appear to work at times, but it's invalid and browser-dependent.
So, here is the parseXML way:
xmlDoc = $.parseXML(string),
$xml = $(xmlDoc),
$title = $xml.find("notes[id='user1']").text();
alert($title);
Live demo.
Here's a JSFiddle. It's simple to do using jQuery if you are using HTML-parsible XML (as seen above).
string = "<user>username 1<notes>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>";
var node = $("<div>" + string + "</div>");
alert(node.find('notes').text());
node.attachTo(document.body); //append to dom?
I would rather go with this approach.
var xml = "<user>username 1<notes>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>";
function FindNotesByUserName(uName) {
var node = $('<div/>').html(xml);
return node.find(":contains('" + uName + "')").closest("user").find("notes").text();
}
var desiredNotes = FindNotesByUserName("username 2");
N.B: This is a minor alteration of what ghayes did. Just to meet OP requirement.
Related
This is my first time doing anything with XML. I'm working with a script (I'm not the original author) that outputs an XML object like so:
var myUrl = <ajaxXmlObject><textarea>"http://examplewebsite.com/?page=home¶meterA=x¶meterB=y"</textarea></ajaxXmlObject>
Is there any way, using jQuery or JavaScript, of accessing the <textarea> node and concatenating a string to the URL? So far my research has come up short.
You can wrap your xml in a jquery object then reference/update the node text.
var myObj = $('<ajaxXmlObject><textarea>"http://examplewebsite.com/?page=home¶meterA=x¶meterB=y"</textarea></ajaxXmlObject>');
var url = myObj.find('textarea').text().replace('"', '').replace('"', '');
url += "&some=stuff";
myObj.find('textarea').text('"' + url + '"')
alert(myObj.find('textarea').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I added some handling to maintain the double quotes. I am not sure if you need that or not.
Using getElementsByTagName in combination with an innerHTML method worked for me. You also need to make sure the new string is formatted properly for XML.
var myUrl = <ajaxXmlObject><textarea>"http://examplewebsite.com/?page=home¶meterA=x¶meterB=y"</textarea></ajaxXmlObject>;
var stringOfNewContent = "&more-stuff&even-more-stuff";
responseUrl.getElementsByTagName('textarea')[0].innerHTML += stringOfNewContent;
This now returns:
responseUrl = <ajaxXmlObject><textarea>"http://examplewebsite.com/?page=home¶meterA=x¶meterB=y&more-stuff&even-more-stuff"</textarea></ajaxXmlObject>
I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;
I've got a string of html that I get via $("#datadiv").html();. Within this data are several other elements, and what I would like to do is append some data to one of those elements.
e.g.
var data = $("#datadiv").html();
var somestring = "Some text"
then append somestring into the div #stringholder inside of data. Is this possible?
And before the question comes, no I can't add it to the div before doing $("#datadiv").html();.
You can do something like this:
$(data).find("#stringholder").append(somestring);
As the html method returns a string, you need to pass it into jQuery again to create a jQuery object. You can then call find to get the element you want, and append to append the other string.
jQuery is quite happy to accept a string of HTML as an argument. It's not just selector strings that are accepted. If you pass in a string of HTML, that fragment will be the context for further method calls.
I think you already know this, but note that this will not affect the HTML in the DOM. It will only affect the fragment produced by passing the string into jQuery.
Do you mean :
var data = $("#datadiv").html();
var somestring = "Some text"
var newData = data + " " + somestring;
var holderData = $("#stringholder").html();
var newestData = holderData + " " + newData;
$("#stringholder").html('');
$("#stringholder").html(newestData);
Sure. Basically you could dump the string from the current div in to a variable and then concate the additional text and put it back in the div.
var someText = $('#datadiv').html()
var someNewText = 'my new text'
var someText = someText + ' ' + someNewText
$('#datadiv').html('') //this will clear the current text but not really necessary.
$('#datadiv').html('someText')
you just need to have some event that fires to trigger everything.
I have one string
var str = '';
str += 'category='+jv('category')+'&';
str += 'refresh_rate='+jv('refreshRate')+'&';
str += 'submit=Y';
now I want to take values from jv('category') and jv('refreshRate') in separate string in javascript (I want to extract values after "=" and before "&").
Thanks.
I've used this: http://blog.stevenlevithan.com/archives/parseuri
URI Parser in the past and find it simple to use and it doesn't rely on any other libraries. Its also pretty lightweight.
The author has a demo page but doesn't really explain how to use it..
Its really simple, you just do something like this:
var url = "http://my-site.com:8081/index.html?query=go&page=2";
var parsed = parseUri(url);
From there you can get things like the host/protocol/port/etc..
When dealing with the querystring you do
var page = parsed.queryKey.page;
alert(page); //alerts 2
Click the parse button on the demo page to see all properties of the parsed URI object that you can access..
You can use http://github.com/allmarkedup/jQuery-URL-Parser or any other URL parser for this sort of string.
$('img').click(function(){
var add_to_list = $(this);
// database query for element
});
Currently add_to_list is getting the value 'images/image.jpg'. I want to replace the 'image/' to nothing so I only get the name of the picture (with or without the extension). How can I do this? I couldn't find anything. Also please provide me with further reading on string manipulation please.
Have you tried javascript replace function ?
You should modify your code to something like this:
$('img').click(function(){
var add_to_list = $(this).attr('src').replace('images/', '');
// database query for element
});
use
add_to_list.substring(7);
This will get you the string after the 7th character. If there might be longer paths, you can split() into an array and get the last part of the path using pop().
add_to_list.split("/").pop();
substring
split
pop
This tutorial explains many of the string manipulation methods seen in the answers here.
$('img').click(function(){
var add_to_list = $(this).attr('src').replace('image/', '');
// database query for element
});
var pieces = add_to_list.split('/');
var filename = pieces[pieces.length-1];