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

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

Related

issue when trying to split url in js

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).

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]);

Getting the url parameters inside the html page

I have a HTML page which is loaded using a URL that looks a little like this:
http://localhost:8080/GisProject/MainService?s=C&o=1
I would like to obtain the query string parameters in the URL without using a jsp.
Questions
Can this be done using Javascript or jQuery?
Because I want to test my page using my Node.js local server before deploying it in the remote machine which uses a Java server.
Is there any library that will allow me to do that?
A nice solution is given here:
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample:
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');`
Chrome 49 implements URLSearchParams from the URL spec, an API which is useful for fiddling around with URL query parameters. The URLSearchParams interface defines utility methods to work with the query string of a URL.
So what can you do with it? Given a URL string, you can easily extract parameter values as in the code below for s & o parameter:
//http://localhost:8080/GisProject/MainService?s=C&o=1
const params = new URLSearchParams(document.location.search);
const s = params.get("s");
const o = params.get("o");
console.info(s); //show C
console.info(o); //show 1
Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, we can grab the query string using window.location.search:
const queryString = window.location.search;
console.log(queryString);
// ?product=shirt&color=blue&newuser&size=m
We can then parse the query string’s parameters using URLSearchParams:
const urlParams = new URLSearchParams(queryString);
Then we call any of its methods on the result.
For example, URLSearchParams.get() will return the first value associated with the given search parameter:
const product = urlParams.get('product')
console.log(product);
// shirt
const color = urlParams.get('color')
console.log(color);
// blue
const newUser = urlParams.get('newuser')
console log(newUser);
// empty string
Other Useful Methods
Let's get a non-encoded URL for example:
https://stackoverflow.com/users/3233722/pyk?myfirstname=sergio&mylastname=pyk
Packing the job in a single JS line...
urlp=[];s=location.toString().split('?');s=s[1].split('&');for(i=0;i<s.length;i++){u=s[i].split('=');urlp[u[0]]=u[1];}
And just use it anywhere in your page :-)
alert(urlp['mylastname']) //pyk
Even works on old browsers like ie6

Get Query String with Dojo

Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
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 the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.

Categories