Find any variable that is undefined and hide from url string - javascript

I'm currently building a URL string from form inputs to look something similar to this:
api/search/127879/11-28-2013/7/2/undefined/undefined/undefined/LGW/null
How would i find any or all variables that === to undefined and then remove from these from the string above?

if you dont want to chage logic of building url than just make use of replace function of javascript
var str = "api/search/127879/11-28-2013/7/2/undefined/undefined/undefined/LGW/null";
var res = str.replace(/undefined\//gi,"");

If you are generating string yourself, then check before appending it to urlString.
If you get the string from server, then do this:
var finalUrl = "";
var urlStr= "api/search/127879/11-28-2013/7/2/undefined/undefined/undefined/LGW/null";
var urlArray = urlStr.split('/');
for (i = 0, i = urlArray.length; i ++) {
if(urlArray[i] === undefined)
{
//do nothing
}
else
{
finalUrl += urlArray[i];
}
}
Hope this helps.

Related

Converting a badly stringfied json to a json object

I have some data i am pulling from a web service. This is the string
(Body:'3886' MessageProperties [headers={}, timestamp=null,
messageId=null, userId=null, receivedUserId=null, appId=null,
clusterId=null, type=null, correlationId=null,
correlationIdString=null, replyTo=null,
contentType=application/x-java-serialized-object,
contentEncoding=null, contentLength=0, deliveryMode=null,
receivedDeliveryMode=PERSISTENT, expiration=null, priority=0,
redelivered=false, receivedExchange=,
receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62,
messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg,
consumerQueue=bottomlesspit])
It looks like json but the key value pairs are almost fine but the most important key which is Body isn't like other keys as the string would tell.
I need to read the value of Body and be able to get the value like this
console.log(d.body);
//This above outputs the string as shown
obj = eval('{' + d.body + '}');
console.log(obj);
var match = "Body";
var val = obj.find( function(item) { return item.key == match } );
console.log(val);
How can i read the value of the key Body?.
Use this regular expression instead of a match Body:
\bBody:'(\d*)'
This will catch the Body number in group 1.
You can write a parser function get string and extract values. A very simple function is here. You can modify it also for all exceptions exist.
var str = `(Body:'3886' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=application/x-java-serialized-object, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62, messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg, consumerQueue=bottomlesspit])`;
function f(inp) {
var index = str.indexOf(inp),
endIndex;
for(var i = index; i < str.length; i ++) {
if(str[i] == ',') {
endIndex = i;
break;
}
}
var output = str.substr(index, endIndex).split('=');
return output;
}
console.log(f('consumerQueue'));
Why not use a regex to match and extract the Body.
Example:
const match = d.body.match(/Body:\'(.+)\'/)
if (match) {
const body = match[1] // This is the value of Body
} else {
// Unable to find Body, handle it here
}

How to find url parameter # with value in javascript

I need to find url parameter # with value in javascript.
my url is like:
http://rohitazad.com/wealth/tax/how-to-file-your-income-tax-return/newslist/34343443.cms?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer
i want to find this value #sid53239948
I find this How can I get query string values in JavaScript?
but how to find this value in url?
EDIT:
This will filter the sid into the sid-variable wherever you put your hash.
var url_arr = window.location.hash.split('&'),
sid = '';
url_arr.filter(function(a, b) {
var tmp_arr = a.split('#')
for (var i in tmp_arr)
if (tmp_arr[i].substring(0, 3) == 'sid')
sid = tmp_arr[i].substring(3, tmp_arr[i].length)
});
console.log(sid) // Will output '53239948'
Old answer:
var hash_array = window.location.hash.split('#');
hash_array.splice(0, 1);
console.log(hash_array);
use this plugin that help you to find exact information
https://github.com/allmarkedup/purl
Try this way,
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
// console.log(window.location.href);
// console.log(hashes);
for(var index = 0; index < hashes.length; index++)
{
var hash = hashes[index].split('=');
var value=hash[1];
console.log(value);
}
http://www.w3schools.com/jsref/jsref_indexof.asp
Search a string for "welcome":
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
The result of n will be:13. Maybe this helps you. In the posted link in your question you see how you get the url. But be careful: indexOf only returns the 1st occurence.
The post you have referenced is looking for a URL parameter in a string. These are indicated by:
?{param_name}={param_value}
What you are looking for is the anchor part of the URL or the hash.
There is a simple Javascript function for this:
window.location.hash
Will return:
#sid53239948
See reference:
http://www.w3schools.com/jsref/prop_loc_hash.asp
However, given a URL that has multiple hashes (like you one you provided), you will need to then parse the output of this function to get the multiple values. For that you will need to split the output:
var hashValue = window.location.hash.substr(1);
var hashParts = hashValue.split("#");
This will return:
['sid53239948', '%kjimwer']
Since you have hash values in query params, window.location.hash will not work for you. You can try to create an object of query parameters and then loop over them and if # exists, you can push in a array.
Sample
function getQStoObject(queryString) {
var o = {};
queryString.substring(1).split("&").map(function(str) {
var _tmp = str.split("=");
if (_tmp[1]) {
o[_tmp[0]] = _tmp[1];
}
});
return o
}
var url = "http://rohitazad.com/wealth/tax/how-to-file-your-income-tax-return/newslist/34343443.cms?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer";
// window.location.search would look like this
var search = "?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer";
var result = getQStoObject(search);
console.log(result)
var hashValues = [];
for(var k in result){
if(result[k].indexOf("#")>-1){
hashValues.push(result[k].split('#')[1]);
}
}
console.log(hashValues)
`
This solution will return you both values following #.
var url = 'http://rohitazad.com/wealth/tax/how-to-file-your-income-tax-return/newslist/34343443.cms?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer';
var obj = url.split('?')[1].split('&');
for(var i = 0; i < obj.length; i++) {
var sol = obj[i].split('#');
if(sol[1]) {console.log(sol[1]);}
}

Adding parameters to url

I try to test the function s.Util.getQueryParam.
The url I have is in format
http://project1/project1.html
I would like to add some parameters in the url after that in order to have something like this format
http://project1/project1.html/?id=03
I try to use this example
// www.mysite.com/my_app.html?Use_Id=abc
var GET = {};
var query = window.location.search.substring(1).split("&");
for (var i = 0, max = query.length; i < max; i++)
{
if (query[i] === "") // check for trailing & with no param
continue;
var param = query[i].split("=");
GET[decodeURIComponent(param[0])] = decodeURIComponent(param[1] || "");
}
I try to add in Get this id=03 but it is not working when I refresh my browser I can't see the parameter. Is it possible to help me how can I run it with the right way?
You can modify window.location.search to add query parameters. This will cause the browser to load the new URL (the page will be refreshed).
Example: window.location.search = '?id=03'.

Get string from url using jQuery?

Say I have http://www.mysite.com/index.php?=332
Is it possible to retrieve the string after ?= using jQuery? I've been looking around Google only to find a lot of Ajax and URL vars information which doesn't seem to give me any idea.
if (url.indexOf("?=") > 0) {
alert('do this');
}
window.location is your friend
Specifically window.location.search
First your query string is not correct, then you can simply take the substring between the indexOf '?=' + 1 and the length of the string. Please see : http://www.w3schools.com/jsref/jsref_substring.asp
When it is easy to do without JQuery, do it with js only.
here is a code snippet (not by me , don't remember the source) for returning a value from a query string by providing a name
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results)
{ return 0; }
return results[1] || 0;
}
var myArgs = window.location.search.slice(1)
var args = myArgs.split("&") // splits on the & if that's what you need
var params = {}
var temp = []
for (var i = 0; i < args.length; i++) {
temp = args[i].split("=")
params[temp[0]] = temp[1]
}
// var url = "http://abc.com?a=b&c=d"
// params now might look like this:
// {
// a: "a",
// c: "d"
// }
What are you trying to do? You very well may be doing it wrong if you're reading the URL.

Can a javascript attribute value be determined by a manual url parameter?

I am trying to display data from an external .jsp file, which is set up something like this:
<tag>
<innertag1 id="1">
<innertag1 id="2">
</tag>
<tag>
<innertag2 id="3">
<innertag2 id="4">
</tag>
To display only information from only one particular "innertag" tag, I'm currently using:
NodeList labs = XMLInfo.getElementsByTagName("innertag1");
I'd like to be able to isolate any particular tag with ease. Theoretically, I could create many individual pages and simply change the values to "innertag2," "innertag3," etc., but this is obviously a bit impractical.
Is there a way to determine the value via a URL parameter? For instance, if I wanted to only display data from "innertag2," is there a way that the url http://www.server.com/data.jsp?id=innertag2 would adjust the tagname properly?
Thank you, any help would be much appreciated.
You can parse document.location.href and extract parameters from there. This is from an old HTML file where I used this technique (not sure if it's compatible on all browsers, however).
var args = {};
function parseArgs()
{
var aa = document.location.href;
if (aa.indexOf("?") != -1)
{
aa = aa.split("?")[1].split("&");
for (var i=0; i<aa.length; i++)
{
var s = aa[i];
var j = s.indexOf("=");
if (j != -1)
{
var name = s.substr(0, j);
var value = s.substr(j + 1);
args[name] = value;
}
}
}
}
Not sure if this is what you're looking for, but you can access parameters from the url using location.search.
6502's answer is almost good enough, it's not url decoding parameters. The function below is a bit more polished (descriptive variable names, no global variables)
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do
var params = getUrlParams();
XMLInfo.getElementsByTagName(params['id']); // or params.id

Categories

Resources