issue when trying to split url in js - javascript

Hi guys I am trying to take token from url.
I am trying this code
const userURL = document.location;
const shared_token = userURL.split('/')[4].split('?')[0];
alert(shared_token)
my url is something like this:
http://www.something.com/earlyAccessPage/%217y%2299%24SYE8FJ7s9oVWix1i6HSC9ega21nXhhOty0UbgrX09jQhssmXMPhXK?fbclid=IwAR2cFvZgJAJsm1zaaRVdb20vzGzZg1qnazTtW-9Bm25DIsiSkdIBEKdjNfo
But it's show error: userURL.split is not a function. Please help me to correct my code.

Use location.pathname - that can be document.location or window.location - either will work for you: Location object
location.pathname.split("/").pop()
returns
%217y%2299%24SYE8FJ7s9oVWix1i6HSC9ega21nXhhOty0UbgrX09jQhssmXMPhXK
Using your code:
const userURL = document.location;
const shared_token = userURL.pathname.split('/').pop(); // take the last part of the path
alert(shared_token)
NOTE In the example I use new URL() to make a URL from the URL you provided. You just need document.location
// const shared_token= location.pathname.split("/").pop() in your real code
const shared_token= new URL("http://www.something.com/earlyAccessPage/%217y%2299%24SYE8FJ7s9oVWix1i6HSC9ega21nXhhOty0UbgrX09jQhssmXMPhXK?fbclid=IwAR2cFvZgJAJsm1zaaRVdb20vzGzZg1qnazTtW-9Bm25DIsiSkdIBEKdjNfo")
.pathname
.split("/")
.pop()
console.log(shared_token)
To get parameters AFTER the ? use
// const url = location
const url = new URL("http://www.something.com/earlyAccessPage/%217y%2299%24SYE8FJ7s9oVWix1i6HSC9ega21nXhhOty0UbgrX09jQhssmXMPhXK?fbclid=IwAR2cFvZgJAJsm1zaaRVdb20vzGzZg1qnazTtW-9Bm25DIsiSkdIBEKdjNfo")
const usp = new URLSearchParams(url.search)
const fbclid = usp.get("fbclid")
console.log(fbclid)

this is wrong. document.location returns location object. you are try to split location object. so instead of that try to use const url = document.URL.
ref : Document.URL
const userURL = document.URL;
const shared_token = userURL.split('/')[4].split('?')[0];
alert(shared_token)

You get a Location object back from document.location which already splits up the url for you in handy ways. See the docs for details, but it looks like userURL.search would give you what's after the question mark. So your code could simply to:
// if you want the first value after the '?' you can do this:
const search = document.location.search;
const firstSearch = search ? search.substring(1).split("&")[0] : "";
// if you want the value immediately before the '?' you can do this:
const segments = document.location.pathname.split("/");
const lastSegment = segments[segments.length-1];
You can always use the original userURL.href but see the various parts of Location that are already prepared for you (like host, port, pathname and search).

Related

how to replace/ remove a substring if a string contains that substing

I am writing a function that detects if the current URL contains a certain substring. If it contains, then I would like to remove it.
For example,
localhost/4000?ab=2&item=google
localhost/4000?ab=2&item=google123
localhost/4000?ab=2&item=google1233&haha=helpful
My idea is below....but kinda stuck in the process
function changeUrl(item) {
var currentUrl = window.location.href;
if(currentUrl.includes('&item=') ){
.....
.....
return currentUrl
}else return;
}
I wouldn't try to manipulate it as a string. JavaSccript has a perfectly good tool to manipulate URLs, and you might as well use it:
str = 'http://localhost/4000?ab=2&item=google1233&haha=helpful';
url = new URL(str);
url.searchParams.delete('item'); // Idempotent call
result = url.toString();
In this case, it's better to use URLSearchParams.
MDN DOCS
The URLSearchParams interface defines utility methods to work with the query string of a URL.
var url = new URL('https://example.com?foo=1&bar=2');
var params = new URLSearchParams(url.search);
// you can see params by this way
for (let p of params) {
console.log(p);
}
// if you want to check if some params are exist
console.log(params.has('foo')); // true
// if you want to delete some params
console.log(params.toString());
params.delete('foo');
console.log(params.toString());

How to Change URL With JavaScript

If a person came to my site, they will find multiple instances of following URL in a hyperlink:
https://example.com/_layouts/15/listform.aspx?PageType=6&ListId=%7B6DDF7ABCX%2D5A27%2D4BEB%2DB4F9%2D158FAA3F0B34%7D&ID=14
I want to use JavaScript to replace the above URL on load to the below.
https://example.com/Lists/Your%20Col/Item/editifs.aspx?ID=14&Source=https://example.com/Lists/Your%20Col/AO12.aspx&DefaultView=AO
The ID can change depending on the ID of the item. How can I replace the URL and preserve the ID in the new URLs?
I tried finding a tutorial and came up with the below, but no luck
<script>
var ourInterestingString = “https://example.com/_layouts/15/listform.aspx?PageType=6&ListId=%7B6DDF7ABCX%2D5A27%2D4BEB%2DB4F9%2D158FAA3F0B34%7D&ID=14”;
var ourNewString = ourInterestingString
.replace(“https://example.com/_layouts/15/listform.aspx?PageType=6&ListId=%7B6DDF7ABCX%2D5A27%2D4BEB%2DB4F9%2D158FAA3F0B34%7D&”, “https://example.com/Lists/Your%20Col/Item/editifs.aspx?”)
console.log(ourNewString);</script>
You could parse the URL with URLSearchParams.
const old_url = "https://example.com/_layouts/15/listform.aspx?PageType=6&ListId=%7B6DDF7ABCX%2D5A27%2D4BEB%2DB4F9%2D158FAA3F0B34%7D&ID=14";
const searchParams = new URLSearchParams(old_url);
const ID = searchParams.get("ID");
const new_url = `https://example.com/Lists/Your%20Col/Item/editifs.aspx?ID=${ID}&Source=https://example.com/Lists/Your%20Col/AO12.aspx&DefaultView=AO`;
console.log(new_url);

how to replace part of a string with a const?

Thats my code:
const searchTerm = `?term=${this.term}`;
const routeWithoutTerm = this.$route.fullPath.replace(searchTerm , '');
I want to remove searchTerm from this.$route.fullPath and save it in routeWithoutTerm, but this is obviously the wrong way. It just replaces nothing. How can I achieve this?
EDIT: Lets just say that at execution this.term = 'help' and this.$route.fullPath = 'search/help?term=help' and I want to remove ?term=help
I finally found my problem.
I was having umlauts(ö, ä, ü) in my searchTerm so I had to use encodeURI() on my searchTerm first.
try this to remove search param:
const url = 'https://example.com/posts?page=5&sort=desc';
const urlObj = new URL(url);
urlObj.search = '';
const result = urlObj.toString();
console.log(result); // https://example.com/posts
source
Use substring() function to get the part you want and use replace() to replace it with whatever you want
const const1 = "adios";
const const2 = "muchasgracias";
var result = const2.replace(const2.substring(0,5), const1);
console.log(result);

Getting URL parameters and filter out a specific parameter

I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);

Remove one of URL query strings which passed to URL as array?

Here is the URL :
www.example.com/?param%5B%5D=A&param%5B%5D=B
the %5B%5D part is [] to pass param as an array, which is encoded in url.
Now, I want to remove one of parameters , desired output is:
www.example.com/?param%5B%5D=B
I have searched for this but found nothing!
All the answers are about removing a single value parameter, not multiple.
UPDATE:
I don't know the exact position of the parameter, i.e the URL could be something like this:
www.example.com/?test=124&test2=456&param%5B%5D=A&param%5B%5D=B
You can take advantage of URL WebAPI.
https://developer.mozilla.org/en-US/docs/Web/API/URL
var base = 'http://www.example.com/'
var query = '?param%5B%5D=A&param%5B%5D=B';
var url = new URL(base + query);
var params = new URLSearchParams(url.search);
var filteredParams = params.getAll('param[]')
.filter(function(el) {
return el !== "A";
}).map(function(el){
return ['param[]', el];
});
var newParams = new URLSearchParams(filteredParams);
var url = new URL(base + '?' + newParams.toString() );
console.log(url.toString());
Here is an example on how to extract the params from the URL.
Now how to use them on a user user interaction form (UI) is up to you.
// Use this to get the document location:
var ActualURL = document.location.href;
console.log("This snippet URL: "+ActualURL);
// Only for this demo, I "simulate" a URL.
// ActualURL is overwritten here.
var ActualURL = "www.example.com/?param%5B%5D=A&param%5B%5D=B";
console.log("FAKED URL: "+ActualURL);
var domain = ActualURL.split("?")[0];
console.log("Domain: "+domain);
var params = ActualURL.split("?")[1];
var param_array = params.split("&");
for (i=0;i<param_array.length;i++){
console.log( "Param #"+i+": "+param_array[i] );
}
console.log("Rebuilted URL with only param #2: "+domain+"?"+param_array[1]);

Categories