How to extract values using javascript? - javascript

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.

Related

How to add a variable to a regex checking for a URL?

I have this part of a function which is running perfectly:
if(/https?:\/\/[a-z]{2}w?\.mywebsite\./.test(href)){
if(!firstSerp){
firstSerp = this;
add_prerender(this, href);
}
}
As you can see mywebsite is hard-coded. What I want is to put a variable there instead.
So it would look like this:
var mylink = 'mywebsite';
if(/https?:\/\/[a-z]{2}w?\.+= mylink\./.test(href)){}
One of the users suggested I look at How do you use a variable in a regular expression?
var replace = "regex";
var re = new RegExp(replace,"g");
But I have difficulties understanding how that would apply to my example.
Could you please help me solve this?
Regular expressions are intended to be used to check if an existing string matches a pattern or to find a pattern in an existing string. You cannot use them to build a string.
Instead, you should use string concatenation:
const url = 'http://www.' + mywebsite + '.com';
or a string template:
const url = `http://www.${mywebsite}.com`;

Adding a string inside a node of an XML object using JavaScript or jQuery

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&parameterA=x&parameterB=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&parameterA=x&parameterB=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&parameterA=x&parameterB=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&parameterA=x&parameterB=y&more-stuff&even-more-stuff"</textarea></ajaxXmlObject>

How to escape JSON in an HTML string stored as a Javascript variable?

I'm trying to parse a JSON string and I can't get it to work because of illegal chracters - which I cannot find...
Here is what I have:
make = function (el) {
var config = el.getAttribute("data-config");
console.log(config);
var dyn = $.parseJSON(config)
console.log(dyn);
}
var a= document.createElement("Star Icon");
console.log(a);
make(a);
I'm not really sure how to correctly unescape the JSON in my original string "a", so that it works.
Question_:
Which quotation marks do I need to escape to get this to work?
Thanks!
EDIT:
Ok. I figured it out using Jquery (I'd prefer Javascript-only though). This works:
make = function (el) {
var config = el.attr("data-config");
console.log(config);
var dyn = $.parseJSON(config)
console.log(dyn);
}
var c = $('<a href="#" class="template" data-config=\'{"role":"button","iconpos":"left","icon":"star","corners":"false","shadow":"false", "iconshadow":"false", "theme":"a","class":"test", "href":"index.html","text":"Star Icon", "mini":"true", "inline":"true"}\'>Star Icon</a>')
console.log(c);
make(c);
So escaping the start/end quotations of the JSON string seems to do the trick. The actual problem was that I can not use document.createElement with a full string. I can only create the element document.createElement(a) and then set innerHTML. Need to look into this some more.
If someone can tell me a Javascript-only way how to do this, please let me know.
Thanks!
Strings and object keys in JSON must be double quoted. Double quotes in attributes are not valid, so you'll need to escape them with ".
Also, you probably want to use booleans true/false instead of strings "true"/"false".
var a = document.createElement('Star Icon');
Notice this is completely unreadable and #millimoose's suggestion about just setting the attribute afterwards will make this much easier to deal with in the long run.

Parsing an HTML like String in Javascript or JQuery

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.

Search for a word and replace everything behind it

I hava a url like
mysite.net/home/index/page/XX
while XX is any number. I need to replace XX and remove everything that might be behind XX. So I would like to remove everything behind page/ by replacing it with a number.
There are a lot of methods for string manipulation http://www.w3schools.com/jsref/jsref_obj_string.asp
I know how to perform this but I am not sure which methods to use. So I ended with getting the lastIndexOf("page/"). So this +1 would give me the starting point for replacing the string. The entire length of the string would be the ending point.
Any ideas?
The following code will do the trick, by using regular expression:
"mysite.net/home/index/page/XX".replace(/\/page\/.*/, '/page/123')
var url = "mysite.net/home/index/page/XX"
return url.substr(-(url.length - (url.lastIndexOf("page/") + 5))))
I don't get your problem because you may have found everything you need...
var yourURI = "mysite.net/home/index/page/XX";
var theDelimiter = "page/";
var yourNewIndex = "42";
var yourNewURI = null;
var lastIndexOfDelimiter = yourURI.lastIndexOf(theDelimiter);
if (lastIndexOfDelimiter != -1)
{
yourNewURI = yourURI.substr(0, lastIndexOfDelimiter + theDelimiter.length) + yourNewIndex;
}
Is that what you want?
This isn't a direct answer to your question, but the way I solve this kind of problem is to have the server calculate a 'base url' (mysite.net/home/index/page/ in your case), and write it to a js variable at the time the page is built.
For two different ASP.NET MVC versions (there would be something similar you could do in any other framework) this looks like this:
var baseUrl = '#ViewBag.BaseUrl';
or
var baseUrl = '<%: ViewData["BaseUrl"] %>';
This has the big advantage that the page JS doesn't start to know about URL formation, so if you change your URL routing you don't find little breakages all over the place.
At least for ASP.NET MVC, you can use the frameworks routing API to generate the base URL at the server side.

Categories