Javascript that removes part of string / url query parameters - javascript

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

Related

Redirect to another website (New ur has parameter) and add on current parameters (how to remove ? and add just &)

I'm passing URL parameters from the current link to another link but the new parameters are added as "&?firstName=test&lastName=testing" and should be just "&firstName=test&lastName=testing"
<script>
$('#redirectButton').click(function() {
const url = window.location.href;
const params = url.split('/');
const parameter = params[params.length-1];
const page2 = "www.newwebsite.com/page?existingParam=true" +parameter;
window.location.href = page2
});
</script>
If your URL is something like www.mywebsite.com/blah/blahblah/test?a=1&b=2, then the last item of the split list would be test?a=1&b=2. Blindly adding this to something like www.myotherwebsite.com/blah/test?existing=true would give www.myotherwebsite.com/blah/test?existing=truetest?a=1&b=2. However, you only want a=1&b=2 to be added (and of course, an & before all that). Thus, we can split by ? and add & plus the last part.
let url = 'www.mywebsite.com/blah/blahblah/test?a=1&b=2';
let redirectURL = 'www.myotherwebsite.com/blah/test?existing=true';
let splitL = url.split('/');
console.log('Redirecting to...');
console.log(redirectURL + '&' + splitL[splitL.length - 1].split('?')[1]);
This is assuming that your URL is not like www.someotherwebsite.com/test?a=1&text=Hello,%20how%20are%20you%20doing? with a question mark in the parameters. If it is, then you should use indexOf to find the index of the first question mark in splitL[splitL.length - 1], and use a slice from that index (plus 1) instead.

remove parameter from url via regex

I have a function for removing the parameter from url.
this is my function :
function removeParameter(key) {
let parameters = document.location.search;
const regParameter = new RegExp('[?|&]' + key + "=([a-zA-Z0-9_-]+)");
if (regParameter.test(parameters)){
parameters = parameters.replace(regParameter , '')
}
window.history.pushState({}, '', parameters)}
when I call this function for the url like this
http://example.com/products?color=4&brand=apple
first call function for removing the brand is correct result
removeParameter('brand')
but another call this function for removing the color doesn't work correctly.
actually when i want to removing the first parameter(key come's after ? mark) this function doesn't work...
The third argument to pushState() is the entire URL. Your function is sending only the location.search i.e. query parameter part of the URL. So you'll need to do
window.history.pushState({}, '', location.pathname + parameters)}
on your function's last line. Also, your code is currently not handling the edge cases i.e. if you remove first parameter, it removes the ? and not the trailing &. So you end up with http://example.com/products&brand=apple which isn't a valid URL. And finally, I simplified your expression a bit.
const reg = new RegExp('[?&](' + key + '=[\\w-]+&?)');
let matches = reg.exec(parameters);
if (matches){
parameters = parameters.replace(matches[1], '');
}
This still doesn't handle more complex cases (params without values, hash etc). There are a couple of other options:
Dump the regex and go with a split('&') based solution. More code, but a lot more readable and less error-prone.
If you don't need IE support, use URLSearchParams. Then your entire function can be reduced to this:
var params = new URLSearchParams(location.search);
params.delete(key);
window.history.pushState({}, '', location.pathname + "?" + params.toString());
Correct me if I'm wrong,
I made a working snippet out of your code, and it seems to work correctly.
If you run the snippet on a fresh new tab, it will add 2 urls in the tab history.
I also modified your regex to make it easier.
function removeParameter(key) {
var parameters = url; // document.location.search; // TAKIT: modified for test
const regParameter = new RegExp('[?|&]' + key + "=([^&]+)"); // TAKIT: Simplified regex
if (regParameter.test(parameters)) {
parameters = parameters.replace(regParameter, '')
}
window.history.pushState({}, 'Test 1', parameters);
return parameters; // TAKIT: Added
}
// Output
var url = "https://stacksnippets.net/js?color=4&brand=apple";
console.log(url);
url = removeParameter("brand");
console.log(url);
url = removeParameter("color");
console.log(url);
Hope it helps.
This function can be used, i modified #Takit Isy answer
function removeParameter(key) {
var parameters = url; // document.location.search; // TAKIT: modified for test
const regParameter = new RegExp(key + "=([a-zA-Z0-9_-]+[&]{0,1})");
if (regParameter.test(parameters)) {
parameters = parameters.replace(regParameter, '')
if(parameters.substring(parameters.length-1)=='?' || parameters.substring(parameters.length-1)=='&'){
parameters = parameters.slice(0, -1);
}
}
return parameters; // TAKIT: Added
}

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

Removing parameter values of a url in the next page using javascript only

I need to remove the values from the url after the ? in the next page the moment i click from my first page. I tried a lot of coding but could not get to a rite path. Need help.
The strings ex- Name, JobTitle and Date are dynamically generated values for ref.
Below are the links associated with the code:
Required url
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?
Resultant url:
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
listItem.onclick = function(){
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
//window.location.href = window.location.href.replace("ListCandidateNew", "newOne") + "?" + stringParameter;
window.location.href="file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?"
+ stringParameter;
}
This should work:
var url = file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
var index = url.lastIndexOf("?");
url = url.slice(0, index+1); // index+1 so that "?" is included
Thanks everond for trying and attempting to answer my problem. Well, i have found the solution using window.sessionStorage as i wanted by keeping the string parameter alive to pass the values. Here is the full code:
I have two pages for passing the value from one to another: ListCandidateNew.html and newOne.html
ListCandidateNew.html
listItem.onclick = function()
{
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
window.sessionStorage['Name'] = elementData.name;
window.sessionStorage['JobTitle'] = elementData.job_title;
window.sessionStorage['Date'] = elementData.entered_date;
**newOne.html**
function LoadCandidateDetail()
{
document.getElementById('Name').innerHTML = window.sessionStorage['Name'];
document.getElementById('JobTitle').innerHTML = window.sessionStorage["JobTitle"];
document.getElementById('Date').innerHTML = window.sessionStorage["Date"];
}

JavaScript - splitting window.location.href returns undefined

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

Categories