Parse URL which contain string of two URL - javascript

I've node app and Im getting in some header the following URL and I need to parse it and change the content of 3000 to 4000 ,How can I do that since Im getting "two" URLs in the req.headers.location
"http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A3000%2Flogin%2Fcallback&client_id=x2.node"
The issue is that I cannot use just replace since the value can changed (dynmaic value ,now its 3000 later can be any value...)

If the part of the URL you always need to change is going to be a parameter of redirect_uri then you just need to find the index of the second %3A that comes after it.
Javascript indexOf has a second parameter which is the 'start position', so you can first do an indexOf the 'redirect_uri=' string, and then pass that position in to your next call to indexOf to look for the first '%3A' and then pass that result into your next call for the %3A that comes just before your '3000'. Once you have the positions of the tokens you are looking for you should be able to build a new string by using substrings... first substring will be up to the end of your second %3A and the second substring will be from the index of the %2F that comes after it.
Basically, you will be building your string by cutting up the string like so:
"http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A"
"%2Flogin%2Fcallback&client_id=x2.node"
... and appending in whatever port number you are trying to put in.
Hope this helps.
This code should get you what you want:
var strURL = "http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A3000%2Flogin%2Fcallback&client_id=x2.node";
var strNewURL = strURL.substring(0,strURL.indexOf("%3A", strURL.indexOf("%3A", strURL.indexOf("redirect_uri") + 1) + 1) + 3) + "4000" + strURL.substring(strURL.indexOf("%2F",strURL.indexOf("%3A", strURL.indexOf("%3A", strURL.indexOf("redirect_uri") + 1) + 1) + 3));

Split the return string in its parameters:
var parts = req.headers.location.split("&");
then split the parts into fieldname and variable:
var subparts = [];
for (var i = 1; i < parts.length; i++)
subparts[i] = parts[i].split("=");
then check which fieldname equals redirect_uri:
var ret = -1;
for (var i = 0; i < subparts.length; i++)
if (subpart[i][0] == "redirect_uri")
ret = i;
if (ret == -1)
// didnt find redirect_uri, somehow handle this error
now you know which subpart contains the redirect_uri.
Because I dont know which rules your redirect_uri follows I can't tell you how to get the value, thats your task but the problem is isolated to subparts[ret][1]. Thats the string which contains redirect_uri.

Related

Javascript ID Extracted From String Not Working

Here's the situation:
function STP() { var LOC = window.location.href;
var CSV = LOC.substring(LOC.indexOf(',')+1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length -1 ];
var POS = window.document.getElementById(STR).offsetTop;
alert( STR ); };
Explained:
When the page loads, the onload calls the script.
The script gets the location.href and Extracts the element ID by
creating an array and referencing the last one.
So far so good.
I then use that to reference an element ID to get its position.
But it doesn't work.
The STR alert indicates the proper value when it's placed above POS, not below. The script doesn't work at all below that point when the STR var reference is used.
However if I do a direct reference to the ID ('A01') no problem.
Why does one work and not the other when both values are identical? I've tried other ways like using a hash instead of a comma and can extract the value that with .location.hash, but it doesn't work either.
The problem is that when you do
LOC.substring(LOC.indexOf(',') + 1);
you're putting everything after the , into the CSV variable. But there is a space between the comma and the 'A01'. So, the interpreter reduces it to:
var POS = window.document.getElementById(' A01').offsetTop;
But your ID is 'A01', not ' A01', so the selector fails.
function STP() {
var LOC = 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810, A01';
var CSV = LOC.substring(LOC.indexOf(',') + 1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length - 1];
console.log(`'${STR}'`);
}
STP();
To solve this, you can increase the index by one:
LOC.substring(LOC.indexOf(',') + 2);
But it would probably be better not to put spaces in URLs when not necessary - if possible, send the user to 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810,A01' instead.

Find the index of a string in Javascript with help of first three characters

I have numerous tsv files each with header row. Now one column name in header row is age. In few files, column name is age while in other files it has EOL charcter such as \r \n.
Now how can i use str.indexOf('age') function so that i get index of age irrespective of column name age with EOL character such as \n , \r etc..
Foe eg:
tsv file1:
Name Address Age Ph_Number
file 2:
Name Address Age/r
file 3:
Name Address Age\n
I am trying to find index of age column in each files header row.
However when i do-
header.indexOf('age')
it gives me result only in case of file1 because in other 2 files we have age as age\r and age\n..
My question is how should i find index of age irrespective of \r \n character along with age in header row.
i have following script now:
var headers = rows[0].split('\t');
if (file.name === 'subjects.tsv'){
for (var i = 0; i < rows.length; i++) {
var ageIdColumn = headers.indexOf("age");
console.log(headers)
As I stated in the comments, indexOf() returns the starting position of the string. It doesn't matter what comes after it:
var csvFile1 = 'column1,column2,column3,age,c1r1';
var csvFile2 = 'column1,column2,column3,age\r,c1r1';
var csvFile3 = 'column1,column2,column3,age\n,c1r1';
console.log(csvFile1.indexOf("age"));
console.log(csvFile2.indexOf("age"));
console.log(csvFile3.indexOf("age"));
If you specifically want to find the versions with the special characters, just look for them explicitly:
var csvFile4 = 'column1,age\r,column2,column3,age\n,c1r1';
console.log(csvFile4.indexOf("age\r"));
console.log(csvFile4.indexOf("age\n"));
Lastly, it may be that you are confused as to what, exactly indexOf() is supposed to do. It is not supposed to tell you where all occurrences of a given string are. It stops looking after the first match. To get all the locations, you'd need a loop similar to this:
var csvFile5 = 'column1,age\r,column2,age, column3,age\n,c1r1';
var results = []; // Found indexes will be stored here.
var pos = null; // Stores the last index position where "age" was found
while (pos !== -1){
// store the index where "age" is found
// If pos is not null, then we've already found age earlier and we
// need to start looking for the next occurence 3 characters after
// where we found it last time. If pos is null, we haven't found it
// yet and need to start from the beginning.
pos = csvFile5.indexOf("age", pos != null ? pos + 3 : pos );
pos !== -1 ? results.push(pos) : "";
}
// All the positions where "age" was in the string (irrespective of what follows it)
// are recorded in the array:
console.log(results);

How to get a specific portion of the url using javascript?

var url = window.location.href.toString();
the above line gives me the url of my current page correctly and my url is:
http://localhost/xyzCart/products.php?cat_id=35
However, using javascript how can i get only a portion of the url i.e. from the above url i just want
products.php?cat_id=35
How to accomplish this plz help.I have looked at similar questions in this forum but none were any help for me..
You can sliply use this:
var url = window.location.href.toString();
var newString = url.substr(url.lastIndexOf(".") + 1));
This will result in: php?cat_id=35
Good luck /Zorken17
You can use the location of the final /:
var page = url.substr(url.substr(0, (url + "?").indexOf("?")).lastIndexOf("/") + 1);
(This allows for / in a query string)
You can get your desired result by using javascript split() method.check this link for further detail
https://jsfiddle.net/x06ywtvo/
var urls = [
"http://localhost/xyzCart/products.php?cat_id=35",
"http://localhost/xyzCart/products.php",
"http://www.google.com/xyzCart/products.php?cat_id=37"
];
var target = $('#target');
for(var i=0;i<urls.length;i++){
var index = urls[i].indexOf("xyzCart");
var sub = urls[i].substring(index, urls[i].length);
target.append("<div>" + sub + "</div>");
}
Try the folowing javacript code to get the part you need. It splits up your url by the "/"s and takes the fourth part. This is superior to substr solutions in terms of descriptive clarity.
url.split("/")[4]
Or if url can contain more "/" path parts, then simply take the last split part.
var parts = url.split("/");
console.log( parts[parts.length-1] );
You will get all necessary values in window.location object.
Kindly check on following CodePen Link for proper output.
I have added parameter test=1
Link: http://codepen.io/rajesh_dixit/pen/EVebJe?test=1
Code
(function() {
var url = window.location.pathname.split('/');
var index = 1;
document.write("URL: ");
document.write(window.location.href);
document.write("<br/> Full Path: ");
document.write(window.location.pathname);
document.write("<br/> Last Value:")
// For cases where '/' comes at the end
if(!url[url.length - index])
index++;
document.write(url[url.length-index])
document.write("<br/> Query Parameter: ");
document.write(window.location.search.substring(1));
})()

regex jquery to replace number with link

I have a page of database results where users occasionally type in a reference to another post. (The database is day event tracker for a scheduling office).
The reference to the other post is always the posts ID (format of 001234). We uses these to match events with dockets and other paperwork from truck drivers. It is always a 6 digit number on its own.
<div class="eventsWrapper">
Data from DB is output here using PHP in a foreach loop.
Presents data in similar fashion to facebook for example.
</div>
What I need to do is once the data in the above DIV is loaded, then go through and replace every whole 6 digit number (not part of a number) with the number as a hyperlink.
It is important it only looks for number with a space either side:
EG: Ref 001122 <- like this - not like this -> ignore AB001122
Once I have the hyperlink tag I can make the reference number clickable to take users directly to that post.
I am not that good with regex but think it is something like:
\b(![0-9])?\d{6}\b
I have no idea how to search the DIV and then replace that regex with the hyperlink. Appreciate any help.
(?:^| )\d{6}(?= |$)
You can use this and replace by <space><whateveryouwant>.See demo.
https://regex101.com/r/bW3aR1/7
\b wont works cos A1 is not a word boundary which you want.
Something like this? Make an array of the individual posts and loop through. If there is only ever one ID in a post, you can do without the second loop.
var str = ['Ref 001122 <- like this - not like this -> ignore AB001122', 'Ref 001123 <- like this - not like this -> ignore AB001122', 'Ref 001124 <- like this - not like this -> ignore AB001122'];
var regex = /\b\d{6}\b/g;
for (var j = 0; j < str.length; j++) {
var urls = str[j].match(regex);
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
newString = str[j].replace('' + urls[i] + '', '<a href = ' + url + '>' + urls[i] + '</a>')
}
$('#output').append(newString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="output"></div>

how to get full path of URL including multiple parameters in jsp

Suppose
URL: http:/localhost:9090/project1/url.jsp?id1=one&id2=two&id3=three
<%
String str=request.getRequestURL()+"?"+request.getQueryString();
System.out.println(str);
%>
with this i get the output
http:/localhost:9090/project1/url.jsp?id1=one
but with this i am able to retrieve only 1st parameter(i.e id1=one) not other parameters
but if i use javascript i am able to retrieve all parameters
function a()
{
$('.result').html('current url is : '+window.location.href );
}
html:
<div class="result"></div>
i want to retrieve current URL value to be used in my next page but i don't want to use sessions
using any of above two method how do i retrieve all parameters in jsp?
thanks in advance
Given URL = http:/localhost:9090/project1/url.jsp?id1=one&id2=two&id3=three
request.getQueryString();
Should indeed return id1=one&id2=two&id3=three
See HttpServletRequest.getQueryString JavaDoc
I once face the same issue, It's probably due to the some testing procedure failure.
If it happens, test in a clear environment : new browser window, etc.
Bhushan answer is not equivalent to getQueryString, as it decode parameters values !
I think this is what you are looking for..
String str=request.getRequestURL()+"?";
Enumeration<String> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements())
{
String paramName = paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++)
{
String paramValue = paramValues[i];
str=str + paramName + "=" + paramValue;
}
str=str+"&";
}
System.out.println(str.substring(0,str.length()-1)); //remove the last character from String

Categories