JavaScript - splitting window.location.href returns undefined - javascript

I have the following code JavaScript:
var url = window.location.href;
var link = url.split('?link=');
link[1] = "http://goo.gl/" + link[1];
link[2] = "http://goo.gl/" + link[2];
function ad(){
window.location.href = link[1];
}
function ac(){
window.open(link[2], '_blank');
}
And there is a link:
ACCESS
The problem is that in some computers, the split is not working.
For exemple: If the link is mySite.com/link.html?link=wfijOp?link=atGdj.
It should give me goo.gl/wfijOp and goo.gl/atGdj instead of goo.gl/undefined and goo.gl/undefined.
What is the problem with those computers?

Thanks, #arcyqwerty! I did what you suggested.
Usually ? is used for separating the query string from the path (see
comment above). Try using another separator like link=abcd,efgh,ijkl.
You can use this to get the query string variable. – #arcyqwerty
Go to the answer

Related

Javascript that removes part of string / url query parameters

i use the code below to format some links. Where it can add either a suffix or a prefix to the link. But i have been researching how to remove part of the link.
Example, this link below.
https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html?cgid=Clothing_Jeans_Straight_Boyfriend#promo_id=210802_Jeans&promo_name=BoyfriendStraight_BoyfriendStraight&promo_creative=2107_FG_Denim_Boyfriend_Straight_277x702&promo_position=Jeans_Slide3&start=1
It has superfluous data, everything after
https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html
Isn't needed, how can i remove everything past that point when formatting the links, before adding the suffix or prefix. Thanks in advance for any help!
$("#btnGenerateLinks").on("click", function() {
var valNeed = $("#strngtime").val();
// if (valNeed.trim().length) { // For filter blank string
$('input[name="linktype1"]').each(function() {
$(this).val($(this).data("link") + valNeed);
});
$('input[name="linktype2"]').each(function() {
$(this).val(valNeed + $(this).data("link"));
});
// }
});
Update - Yes all query parameters
Update - Going with a simple split for now
var myArr = valNeed.split("?")[0];
you can use the URL constructor API
let url = "https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html?cgid=Clothing_Jeans_Straight_Boyfriend#promo_id=210802_Jeans&promo_name=BoyfriendStraight_BoyfriendStraight&promo_creative=2107_FG_Denim_Boyfriend_Straight_277x702&promo_position=Jeans_Slide3&start=1"
let instance = new URL(url);
let cleanURL = instance.origin + instance.pathname;
console.log(cleanURL);
// https://www.torrid.com/product/boyfriend-straight-jean---vintage-stretch-medium-wash/14478822.html

How do I get rid of everything, every string before a specified word in jquery?

I'm trying to do a simple string replace in jquery but it seems to be more than just a simple code.
In mygallery have this image link (note the 2x ../)
var imgName= '../../appscripts/imgs/pic_library/burn.jpg';
In browsegallery I have something like this:
var imgName ='../../../../../appscripts/imgs/pic_library/burn.jpg';
and sometimes depending on where do I get the image source from, it can be like this
var imgName = '../appscripts/imgs/pic_library/burn.jpg';
What I'm trying to do is, to get rid of all of those '../', and to gain the imgName like this:
'appscripts/imgs/pic_library/burn.jpg';
So this way I can get the right directory for my mobile app.
Can anyone help me on how to get rid of all those (without even counting) '../'?
Best Regards!
Using the replace method of a string you can remove all cases of the
../
var imgPath = '../../../../../appscripts/imgs/pic_library/burn.jpg';
var imgName = imgPath.replace(/\.\.\//g, '');
console.log(imgName);
Here is a direct answer to your question that does not tie you to the "/appscripts" in your example:
const imgName= '../../appscripts/imgs/pic_library/burn.jpg';
const img = imgName.split('../')
.filter((val) => val !== '')
.join('');
If the desired end path is always the same - just get the unique part (the actual file name) and add it to a string of the path you require. the following usies lastIndexOf to get the actual file name from the relative path and then builds a string to give the desired path plus the file name.
var fileSource = 'appscripts/imgs/pic_library/burn.jpg';
let lastIndex = fileSource.lastIndexOf('/');
let fileName = fileSource.slice(lastIndex + 1, fileSource.length); // gives burn.jpg
let imageSource = 'appscripts/imgs/pic_library/' + fileName;
console.log(imageSource); // gives appscripts/imgs/pic_library/burn.jpg
Thank you all for helping me out.
I finally solved this using imgName.split('/appscripts/');
Like this:
var replaceImg = image.split('/appscripts/');
var finalImageName = "../../../appscripts/"+replaceImg[1];
Thank you again!
You can create a jQuery plugin, i.e: $(...).imagify()
Use a regex to replace that pattern: .replace(/(\.){1,2}\//g, '')
$.fn.imagify = function() {
var src = this.attr('src') || '';
this.attr('src', src.replace(/(\.){1,2}\//g, ''));
};
$('img').imagify();
$('img').each((_, obj) => console.log($(obj).attr('src')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src='../../../../../appscripts/imgs/pic_library/burn.jpg'>
<img src='../appscripts/imgs/pic_library/burn.jpg'>
<img src='./../../appscripts/imgs/pic_library/burn.jpg'>
Resource
How to Create a Basic Plugin

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));
})()

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

Url parsing in javascript and DOM

I am writing a support chat application where I want text to be parsed for urls. I have found answers for similar questions but nothing for the following.
what i have
function ReplaceUrlToAnchors(text) {
var exp = /(\b(https?:\/\/|ftp:\/\/|file:\/\/|www.)
[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1' target='_blank'>$1</a>");
}
that pattern is a modified version of one i found on the internet. It includes www. in the first token, because not all urls start with protocol:// However, when www.google.com is replaced with
<a href='www.google.com' target='_blank'>www.google.com</a>
which pulls up MySite.com/webchat/wwww.google.com and I get a 404
that is my first problem, my second is...
in my script for generating messages to the log, I am forced to do it a hacky way:
var last = 0;
function UpdateChatWindow(msgArray) {
var chat = $get("MessageLog");
for (var i = 0; i < msgArray.length; i++) {
var element = document.createElement("div");
var linkified = ReplaceUrlToAnchors(msgArray[i]);
element.setAttribute("id", last.toString());
element.innerHTML = linkified;
chat.appendChild(element);
last = last + 1;
}
}
To get the "linkified" string to render HTML out correctly I have to use the non-standard .innerHTML attribute of element. I would prefer a way were i could parse the string as tokens - text tokens and anchor tokens - and call either createTextNode or createElement("a") and stitch them together with DOM.
so question 1 is how should I go about www.site.com parsing, or even site.com?
and question 2 is how would could I do this using only DOM?
Another thing you could do is this:
function ReplaceUrlToAnchors(text) {
var exp = /(\b(https?:\/\/|ftp:\/\/|file:\/\/|www.)
[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp, function(_, url) {
return '<a href="' +
(/^www\./.test(url) ? "http://" + url : url) +
'target="_blank">' +
url +
'</a>';
});
}
That is kind-of like your solution, but it does the check for "www" URLs in that callback passed in to ".replace()".
Note that you won't be picking up "stackoverflow.com" or "newegg.com" or anything like that, which I understand may be unavoidable (and even desirable, given the false positives you'd pick up).
Here is what I came up with, perhaps someone has something better?
function replaceUrlToAnchors(text) {
var naked = /(\b(www.)[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|](.com|.net|.org|.co.uk|.ca|.))/ig;
text = text.replace(naked, "http://$1");
var exp = /(\b(https?:\/\/|ftp:\/\/|file:\/\/)([-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|]))/ig;
return text.replace(exp,"<a href='$1' target='_blank'>$3</a>");
}
the first regex will replace www.google.com with http://www.google.com and is good enough for what I am doing. However, I will hold off marking this as the answer because I would also like to make (www.) optional but when I do (www.)? it replaces every word with http://word/

Categories