More efficient way than using lots of else if statements - javascript

I'm trying to find a better way to do this in Javascript:
if ( text === 'amy' ) {
var url = 'http://www.mydomain.com/amylikescats.html';
}
else if ( text === 'dave' ) {
var url = 'http://www.mydomain.com/daveshome.html';
}
else if ( text === 'steve' ) {
var url = 'http://www.mydomain.com/steve2.html';
}
else if ( text === 'jake' ) {
var url = 'http://www.mydomain.com/jakeeatstofu.html';
}
else {
var url = 'http://www.mydomain.com/noone.html';
}
Is there a more code efficient way of doing this?'

Use an object as a map:
var map = {
"amy": 'http://www.mydomain.com/amylikescats.html',
"dave": 'http://www.mydomain.com/daveshome.html',
// etc
};
var text = "whatever";
var url = map[text] === undefined ? 'http://www.mydomain.com/noone.html' : map[text];
This will save you the maximum amount of repeated code, but if you also need to do other stuff than setting url a switch might be more appropriate.

Switch statement!
var url = 'http://www.mydomain.com/noone.html';
switch(text) {
case 'amy': url = 'http://www.mydomain.com/amylikescats.html';
break;
case 'dave': url = 'http://www.mydomain.com/daveshome.html';
break;
case 'steve': url = 'http://www.mydomain.com/steve2.html';
break;
case 'jake': url = 'http://www.mydomain.com/jakeeatstofu.html';
break;
}
Now there is no need for a default clause because you've initialized url before the switch.
Otherwise you could add this:
default: url = 'http://www.mydomain.com/noone.html';
break;

Associative array:
var data = {
amy: 'http://www.mydomain.com/amylikescats.html',
dave: 'http://www.mydomain.com/daveshome.html',
// etc...
}
To use:
var url = data[text];
The else case can be replicate dby the non-existance of the item in the array, so expanding a bit:
var url = '';
if(!(text in data)){
url = 'http://www.mydomain.com/daveshome.html';
}
else{
url = data[text];
}

Store the unique parts in a dictionary and then take it from there:
var map = {
amy: "amylikescats",
dave: "daveshome",
steve: "steve2",
jake: "jakeeatstofu"
};
var url = map[text];
if (!url) {
url = 'http://www.mydomain.com/noone.html';
} else {
url = 'http://www.mydomain.com/' + url + '.html';
}

You could use an object to hold the URLs for different values of text, and then use the || operator when assigning a value to url to use the fallback value if necessary.
var urlsForText = {
'amy': 'http://www.mydomain.com/amylikescats.html',
'dave': 'http://www.mydomain.com/daveshome.html',
'steve': 'http://www.mydomain.com/steve2.html',
'jake': 'http://www.mydomain.com/jakeeatstofu.html'
};
var url = urlsForText[text] || 'http://www.mydomain.com/noone.html';

Related

Adding a Parameter to Url with javascript

I am trying to add the parameter "referer=" to my url corresponding to the trafic referer of a new session.
I used some of the code from this topic... but it keeps reloading the page in a loop... then the url is like :
https://example.com?refere=facebookreferer=facebookreferer=facebook
Note:
I have been using this solution 1 :
function addOrUpdateUrlParam(name, value)
{
var ref = document.referrer;
var refsplit = ref.split(".")[1];
var href = window.location.href;
var regex = new RegExp("[&\\?]" + name + "=");
if(regex.test(href))
{
regex = new RegExp("([&\\?])" + name + "=\\d+");
{
else
{
if(href.indexOf("?") > -1)
window.location.href = href + "&" + name + "=" + value;
else
window.location.href = href + "?" + name + "=" + value;
}
if (refsplit != "example") {
return addOrUpdateUrlParam("referer", refsplit);
}
}
And this solution 2:
function () {
var ref = document.referrer;
var refsplit = ref.split(".")[1];
if (refsplit != "example") {
return location.search += "referer=" + refsplit;
}
}
Edit 1:
Thanks to Prasanth I improved the code to :
function () {
var ref = document.referrer;
var refsplit = ref.split(".")[1];
var currentUrl = location.href;
var url1 = currentUrl += "?referer="+refsplit;
var url2 = currentUrl += "&referer="+refsplit;
if(currentUrl.indexOf("?") < 0) {
return window.location = url1;
} else {
return window.location = url2;
}
}
However, it is returning both conditions :
https://example.com/?referer=facebook&referer=facebook
Edit 2:
So after many attempts, I achieved it by working with the parameters of the url (location.search) instead of the full url (location.href) :
function addRefererParam () {
var ref = document.referrer; //Get Referrer
var refDomain = ref.match(/[^(?:http:\/\/|www\.|https:\/\/)]([^\/]+)/i)[0]; //Extract Referrer Domain name for better readability
var params = location.search; //Get Url parameters
if (refDomain.match(/mydomain|null|undefined/i)) { //check if domain not null or own domain.
return params ;
} else {
return params += "utm_source=" + refDomain; //create new query string with referrer domain
}
}
However, it is no making a persistent query string through browsing... how can I make the new parameters persistent ?
Obtain the url of the current window and after the domain name just concat your url with &referer=value.
var currentUrl = location.href;
var paramsInUrl = currentUrl.split('&');
var flag = true;
for(var i in paramsInUrl)
{
if(!paramsInUrl[i].includes('referer=')
{
continue;
}
else
{
flag = false;
break;
}
}
if(flag)
{
currentUrl += '&referer='+value;
window.location = currentUrl;
}
For what it's worth (because the more generic question of just how to do this generally is what lead me to this post), I've made a 178 byte helper function that takes in an object of the query parameters you want to add to a url for a GET request (in similar format for how you might add headers to a request) and made an npm package for it here: https://www.npmjs.com/package/add-query-params-to-url
Hopefully this is helpful to some.

how to change url parameter value in browser [duplicate]

I have this URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
what I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified (10).
I've extended Sujoy's code to make up a function.
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
Function Calls:
var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');
window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));
Updated version that also take care of the anchors on the URL.
function updateURLParameter(url, param, paramVal)
{
var TheAnchor = null;
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL)
{
var tmpAnchor = additionalURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheAnchor)
additionalURL = TheParams;
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++)
{
if(tempArray[i].split('=')[0] != param)
{
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
else
{
var tmpAnchor = baseURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheParams)
baseURL = TheParams;
}
if(TheAnchor)
paramVal += "#" + TheAnchor;
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
I think you want the query plugin.
E.g.:
window.location.search = jQuery.query.set("rows", 10);
This will work regardless of the current state of rows.
Quick little solution in pure js, no plugins needed:
function replaceQueryParam(param, newval, search) {
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
}
Call it like this:
window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)
Or, if you want to stay on the same page and replace multiple params:
var str = window.location.search
str = replaceQueryParam('rows', 55, str)
str = replaceQueryParam('cols', 'no', str)
window.location = window.location.pathname + str
edit, thanks Luke: To remove the parameter entirely, pass false or null for the value: replaceQueryParam('rows', false, params). Since 0 is also falsy, specify '0'.
To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.
You can use query-string as follows:
// parse the query string into an object
var q = queryString.parse(location.search);
// set the `row` property
q.rows = 10;
// convert the object to a query string
// and overwrite the existing query string
location.search = queryString.stringify(q);
A modern approach to this is to use native standard based URLSearchParams. It's supported by all major browsers, except for IE where they're polyfills available
const paramsString = "site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc"
const searchParams = new URLSearchParams(paramsString);
searchParams.set('rows', 10);
console.log(searchParams.toString()); // return modified string.
Ben Alman has a good jquery querystring/url plugin here that allows you to manipulate the querystring easily.
As requested -
Goto his test page here
In firebug enter the following into the console
jQuery.param.querystring(window.location.href, 'a=3&newValue=100');
It will return you the following amended url string
http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3
Notice the a querystring value for a has changed from X to 3 and it has added the new value.
You can then use the new url string however you wish e.g
using document.location = newUrl or change an anchor link etc
This is the modern way to change URL parameters:
function setGetParam(key,value) {
if (history.pushState) {
var params = new URLSearchParams(window.location.search);
params.set(key, value);
var newUrl = window.location.origin
+ window.location.pathname
+ '?' + params.toString();
window.history.pushState({path:newUrl},'',newUrl);
}
}
you can do it via normal JS also
var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1];
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
if(tempArray[i].indexOf("rows") == -1){
newAdditionalURL += temp+tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;
Use URLSearchParams to check, get and set the parameters value into URL
Here is the example to get the current URL and set new parameter and update the URL or reload the page as per your needs
var rows = 5; // value that you want to set
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
url.search = url.searchParams;
url = url.toString();
// if you want to append into URL without reloading the page
history.pushState({}, null, url);
// want to reload the window with a new param
window.location = url;
2020 Solution: sets the variable or removes iti if you pass null or undefined to the value.
var setSearchParam = function(key, value) {
if (!window.history.pushState) {
return;
}
if (!key) {
return;
}
var url = new URL(window.location.href);
var params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) {
params.delete(key);
} else {
params.set(key, value);
}
url.search = params;
url = url.toString();
window.history.replaceState({url: url}, null, url);
}
Would a viable alternative to String manipulation be to set up an html form and just modify the value of the rows element?
So, with html that is something like
<form id='myForm' target='site.fwx'>
<input type='hidden' name='position' value='1'/>
<input type='hidden' name='archiveid' value='5000'/>
<input type='hidden' name='columns' value='5'/>
<input type='hidden' name='rows' value='20'/>
<input type='hidden' name='sorting' value='ModifiedTimeAsc'/>
</form>
With the following JavaScript to submit the form
var myForm = document.getElementById('myForm');
myForm.rows.value = yourNewValue;
myForm.submit();
Probably not suitable for all situations, but might be nicer than parsing the URL string.
URL query parameters can be easily modified using URLSearchParams and History interfaces:
// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
// Set new or modify existing parameter value.
//queryParams.set("myParam", "myValue");
queryParams.set("rows", "10");
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());
Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:
history.pushState(null, null, "?"+queryParams.toString());
https://zgadzaj.com/development/javascript/how-to-change-url-query-parameter-with-javascript-only
You can use this my library to do the job: https://github.com/Mikhus/jsurl
var url = new Url('site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc');
url.query.rows = 10;
alert( url);
Consider this one:
const myUrl = new URL("http://www.example.com?columns=5&rows=20");
myUrl.searchParams.set('rows', 10);
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10
myUrl.searchParams.set('foo', 'bar'); // add new param
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10&foo=bar
It will do exactly the same thing you required. Please note URL must have correct format. In your example you have to specify protocol (either http or https)
I wrote a little helper function that works with any select. All you need to do is add the class "redirectOnChange" to any select element, and this will cause the page to reload with a new/changed querystring parameter, equal to the id and value of the select, e.g:
<select id="myValue" class="redirectOnChange">
<option value="222">test222</option>
<option value="333">test333</option>
</select>
The above example would add "?myValue=222" or "?myValue=333" (or using "&" if other params exist), and reload the page.
jQuery:
$(document).ready(function () {
//Redirect on Change
$(".redirectOnChange").change(function () {
var href = window.location.href.substring(0, window.location.href.indexOf('?'));
var qs = window.location.href.substring(window.location.href.indexOf('?') + 1, window.location.href.length);
var newParam = $(this).attr("id") + '=' + $(this).val();
if (qs.indexOf($(this).attr("id") + '=') == -1) {
if (qs == '') {
qs = '?'
}
else {
qs = qs + '&'
}
qs = qs + newParam;
}
else {
var start = qs.indexOf($(this).attr("id") + "=");
var end = qs.indexOf("&", start);
if (end == -1) {
end = qs.length;
}
var curParam = qs.substring(start, end);
qs = qs.replace(curParam, newParam);
}
window.location.replace(href + '?' + qs);
});
});
Using javascript URL:
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
window.location = url;
var url = new URL(window.location.href);
var search_params = url.searchParams;
search_params.set("param", value);
url.search = search_params.toString();
var new_url = url.pathname + url.search;
window.history.replaceState({}, '', new_url);
Here I have taken Adil Malik's answer and fixed the 3 issues I identified with it.
/**
* Adds or updates a URL parameter.
*
* #param {string} url the URL to modify
* #param {string} param the name of the parameter
* #param {string} paramVal the new value for the parameter
* #return {string} the updated URL
*/
self.setParameter = function (url, param, paramVal){
// http://stackoverflow.com/a/10997390/2391566
var parts = url.split('?');
var baseUrl = parts[0];
var oldQueryString = parts[1];
var newParameters = [];
if (oldQueryString) {
var oldParameters = oldQueryString.split('&');
for (var i = 0; i < oldParameters.length; i++) {
if(oldParameters[i].split('=')[0] != param) {
newParameters.push(oldParameters[i]);
}
}
}
if (paramVal !== '' && paramVal !== null && typeof paramVal !== 'undefined') {
newParameters.push(param + '=' + encodeURI(paramVal));
}
if (newParameters.length > 0) {
return baseUrl + '?' + newParameters.join('&');
} else {
return baseUrl;
}
}
In the URLSearchParams documentation, there's a very clean way of doing this, without affecting the history stack.
// URL: https://example.com?version=1.0
const params = new URLSearchParams(location.search);
params.set('version', 2.0);
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?version=2.0
Similarily, to remove a parameter
params.delete('version')
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?
let url= new URL("https://example.com/site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc")
url.searchParams.set('rows', 10)
console.log(url.toString())
Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:
window.history.replaceState('object or string', 'Title', 'page.html' + editParams('sorting', ModifiedTimeAsc));
// background functions below:
// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
key = encodeURI(key);
var params = getSearchParameters();
if (Object.keys(params).length === 0) {
if (value !== false)
return '?' + key + '=' + encodeURI(value);
else
return '';
}
if (value !== false)
params[key] = encodeURI(value);
else
delete params[key];
if (Object.keys(params).length === 0)
return '';
return '?' + $.map(params, function (value, key) {
return key + '=' + value;
}).join('&');
}
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
My solution:
const setParams = (data) => {
if (typeof data !== 'undefined' && typeof data !== 'object') {
return
}
let url = new URL(window.location.href)
const params = new URLSearchParams(url.search)
for (const key of Object.keys(data)) {
if (data[key] == 0) {
params.delete(key)
} else {
params.set(key, data[key])
}
}
url.search = params
url = url.toString()
window.history.replaceState({ url: url }, null, url)
}
Then just call "setParams" and pass an object with data you want to set.
Example:
$('select').on('change', e => {
const $this = $(e.currentTarget)
setParams({ $this.attr('name'): $this.val() })
})
In my case I had to update a html select input when it changes and if the value is "0", remove the parameter. You can edit the function and remove the parameter from the url if the object key is "null" as well.
Hope this helps yall
If you want to change the url in address bar:
const search = new URLSearchParams(location.search);
search.set('rows', 10);
location.search = search.toString();
Note, changing location.search reloads the page.
Here is a simple solution using the query-string library.
const qs = require('query-string')
function addQuery(key, value) {
const q = qs.parse(location.search)
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
// if you are using Turbolinks
// add this: Turbolinks.visit(url)
}
// Usage
addQuery('page', 2)
If you are using react without react-router
export function useAddQuery() {
const location = window.location;
const addQuery = useCallback(
(key, value) => {
const q = qs.parse(location.search);
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
},
[location]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
If you are using react with react-router
export function useAddQuery() {
const location = useLocation();
const history = useHistory();
const addQuery = useCallback(
(key, value) => {
let pathname = location.pathname;
let searchParams = new URLSearchParams(location.search);
searchParams.set(key, value);
history.push({
pathname: pathname,
search: searchParams.toString()
});
},
[location, history]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
PS: qs is the import from query-string module.
Another variation on Sujoy's answer. Just changed the variable names & added a namespace wrapper:
window.MyNamespace = window.MyNamespace || {};
window.MyNamespace.Uri = window.MyNamespace.Uri || {};
(function (ns) {
ns.SetQueryStringParameter = function(url, parameterName, parameterValue) {
var otherQueryStringParameters = "";
var urlParts = url.split("?");
var baseUrl = urlParts[0];
var queryString = urlParts[1];
var itemSeparator = "";
if (queryString) {
var queryStringParts = queryString.split("&");
for (var i = 0; i < queryStringParts.length; i++){
if(queryStringParts[i].split('=')[0] != parameterName){
otherQueryStringParameters += itemSeparator + queryStringParts[i];
itemSeparator = "&";
}
}
}
var newQueryStringParameter = itemSeparator + parameterName + "=" + parameterValue;
return baseUrl + "?" + otherQueryStringParameters + newQueryStringParameter;
};
})(window.MyNamespace.Uri);
Useage is now:
var changedUrl = MyNamespace.Uri.SetQueryStringParameter(originalUrl, "CarType", "Ford");
I too have written a library for getting and setting URL query parameters in JavaScript.
Here is an example of its usage.
var url = Qurl.create()
, query
, foo
;
Get query params as an object, by key, or add/change/remove.
// returns { foo: 'bar', baz: 'qux' } for ?foo=bar&baz=qux
query = url.query();
// get the current value of foo
foo = url.query('foo');
// set ?foo=bar&baz=qux
url.query('foo', 'bar');
url.query('baz', 'qux');
// unset foo, leaving ?baz=qux
url.query('foo', false); // unsets foo
I was looking for the same thing and found: https://github.com/medialize/URI.js which is quite nice :)
-- Update
I found a better package: https://www.npmjs.org/package/qs it also deals with arrays in get params.
No library, using URL() WebAPI (https://developer.mozilla.org/en-US/docs/Web/API/URL)
function setURLParameter(url, parameter, value) {
let url = new URL(url);
if (url.searchParams.get(parameter) === value) {
return url;
}
url.searchParams.set(parameter, value);
return url.href;
}
This doesn't work on IE: https://developer.mozilla.org/en-US/docs/Web/API/URL#Browser_compatibility
I know this is an old question. I have enhanced the function above to add or update query params. Still a pure JS solution only.
function addOrUpdateQueryParam(param, newval, search) {
var questionIndex = search.indexOf('?');
if (questionIndex < 0) {
search = search + '?';
search = search + param + '=' + newval;
return search;
}
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
var indexOfEquals = query.indexOf('=');
return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
}
my function support removing param
function updateURLParameter(url, param, paramVal, remove = false) {
var newAdditionalURL = '';
var tempArray = url.split('?');
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var rows_txt = '';
if (additionalURL)
newAdditionalURL = decodeURI(additionalURL) + '&';
if (remove)
newAdditionalURL = newAdditionalURL.replace(param + '=' + paramVal, '');
else
rows_txt = param + '=' + paramVal;
window.history.replaceState('', '', (baseURL + "?" + newAdditionalURL + rows_txt).replace('?&', '?').replace('&&', '&').replace(/\&$/, ''));
}

How to remove some parameters from an URL string?

I have this var storing a string that represents a URL full of parameters. I'm using AngularJS, and I'm not sure if there is any useful module (or maybe with plain JavaScript) to remove the unneeded URL parameters without having to use regex?
For example I need to remove &month=05 and also &year=2017 from:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
Use the URLSearchParams API:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
var urlParts = url.split('?');
var params = new URLSearchParams(urlParts[1]);
params.delete('month');
params.delete('year')
var newUrl = urlParts[0] + '?' + params.toString()
console.log(newUrl);
The advantage of using this API is that it works with and creates strings with correct percent encoding.
For more information, see MDN Developer Reference - URLSearchParams API.
You can use this function that take 2 parameters: the param you are trying to remove and your source URL:
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var url2 = removeParam("month", url);
var url3 = removeParam("year", url2);
console.log(url3);
Alternative solution with a regex
Sure you can use RegExr: ((&)year=([^&]))|((&)month=([^&]))
use:
url = url.replace(/(year=([^&]*))|(month=([^&]*))/g, '');
Read more regex :)...
function removeParam(name, url){
return url.replace('/((&)*' + name + '=([^&]*))/g','');
}
var url = "?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
function removeParam(name, _url){
var reg = new RegExp("((&)*" + name + "=([^&]*))","g");
return _url.replace(reg,'');
}
url = removeParam('year', url);
url = removeParam('month', url);
document.getElementById('url-replace').innerHTML = url;
<div id="url-replace"></div>
Using string replace:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var modifiedUrl = url.replace('&month=05','').replace('&year=2017','');
console.log(modifiedUrl);
You can use the library https://www.npmjs.com/package/query-string
Convert the params to an object and then just use delete params.year delete params.month and convert it back and add it to the original url
const queryString = require('query-string');
console.log(location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
console.log(location.hash);
//=> '#token=bada55cafe'
const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'
location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'
Enhnaced #Mistalis's answer.
Return the value of the last occurrence of a param
Remove the ? of the removed param was the only param
Url encoded the query params to ensure browser stately
function pruneParams(key, url) {
var urlParts = url.split('?');
var rtnUrl = urlParts[0];
var paramParts;
var paramValue;
var params_arr = [];
var queryString = decodeURIComponent(urlParts[1] || '');
if (queryString !== '') {
params_arr = queryString.split('&');
for (var i = params_arr.length - 1; i >= 0; --i) {
paramParts = params_arr[i].split('=');
if (paramParts[0] === key) {
paramValue = paramParts[1];
params_arr.splice(i, 1);
}
}
if (params_arr.length) {
var wasEncoded = url.split('&').length < 2;
rtnUrl = rtnUrl + '?' + (wasEncoded ? encodeURIComponent(params_arr.join('&')) : params_arr.join('&'));
}
}
return { url: rtnUrl, [key]: paramValue, paramCount: params_arr.length > 1 };
}
var u1 = 'http://localhost:4200/member/';
var u2 = 'http://localhost:4200/member/?ts=23423424';
var u3 = 'http://localhost:4200/member/?fooo=2342342asfasf&ts=252523525';
var u4 = 'http://localhost:4200/member?foo=234243&ts=234124124&bar=21kfafjasf&ts=223424234&dd=This Is A Line';
var u5 = 'http://localhost:4200/member?foo%3D234243%26ts%3D2242424%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line';
console.log(pruneParams('ts', u1));
console.log(pruneParams('ts', u2));
console.log(pruneParams('ts', u3));
console.log(pruneParams('ts', u4));
console.log(pruneParams('ts', u5));
// {
// url: 'http://localhost:4200/member/',
// ts: undefined,
// paramCount: false,
// }
// {
// url: 'http://localhost:4200/member/',
// ts: '23423424',
// paramCount: false,
// }
// {
// url: 'http://localhost:4200/member/?fooo=2342342asfasf',
// ts: '252523525',
// paramCount: false,
// },
// {
// url: 'http://localhost:4200/member?foo=234243&bar=21kfafjasf&dd=This Is A Line',
// ts: '234124124',
// paramCount: true,
// }
// {
// url: 'http://localhost:4200/member?foo%3D234243%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line',
// ts: '2242424',
// paramCount: true,
// }
Taken from #Mistalis answer but tidied up. Useful if URLSearchParams API is not available.
const removeUrlParam = function (url, param) {
var parts = url.split('?')
url = parts[0]
if (parts.length !== 2) return url
var qs = parts[1]
if (qs === '') return url
var params = qs.split('&')
for (var i = params.length - 1; i >= 0; i -= 1) {
var key = params[i].split('=')[0]
if (key === param) params.splice(i, 1)
}
return params.length ? url + '?' + params.join('&') : url
}
var url1 = removeUrlParam('/xxxxx', 'a')
var url2 = removeUrlParam('/xxxxx?a=1', 'a')
var url3 = removeUrlParam('/xxxxx?a=1&b=2', 'a')
console.log(url1, url2, url3)

javascript parser for a string which contains .ini data

If a string contains a .ini file data , How can I parse it in JavaScript ?
Is there any JavaScript parser which will help in this regard?
here , typically string contains the content after reading a configuration file. (reading cannot be done through javascript , but somehow I gather .ini info in a string.)
I wrote a javascript function inspirated by node-iniparser.js
function parseINIString(data){
var regex = {
section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
param: /^\s*([^=]+?)\s*=\s*(.*?)\s*$/,
comment: /^\s*;.*$/
};
var value = {};
var lines = data.split(/[\r\n]+/);
var section = null;
lines.forEach(function(line){
if(regex.comment.test(line)){
return;
}else if(regex.param.test(line)){
var match = line.match(regex.param);
if(section){
value[section][match[1]] = match[2];
}else{
value[match[1]] = match[2];
}
}else if(regex.section.test(line)){
var match = line.match(regex.section);
value[match[1]] = {};
section = match[1];
}else if(line.length == 0 && section){
section = null;
};
});
return value;
}
2017-05-10 updated: fix bug of keys contains spaces.
EDIT:
Sample of ini file read and parse
You could try the config-ini-parser, it's similar to python ConfigParser without I/O operations
It could be installed by npm or bower. Here is an example:
var ConfigIniParser = require("config-ini-parser").ConfigIniParser;
var delimiter = "\r\n"; //or "\n" for *nux
parser = new ConfigIniParser(delimiter); //If don't assign the parameter delimiter then the default value \n will be used
parser.parse(iniContent);
var value = parser.get("section", "option");
parser.stringify('\n'); //get all the ini file content as a string
For more detail you could check the project main page or from the npm package page
Here's a function who's able to parse ini data from a string to an object! (on client side)
function parseINIString(data){
var regex = {
section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/,
comment: /^\s*;.*$/
};
var value = {};
var lines = data.split(/\r\n|\r|\n/);
var section = null;
for(x=0;x<lines.length;x++)
{
if(regex.comment.test(lines[x])){
return;
}else if(regex.param.test(lines[x])){
var match = lines[x].match(regex.param);
if(section){
value[section][match[1]] = match[2];
}else{
value[match[1]] = match[2];
}
}else if(regex.section.test(lines[x])){
var match = lines[x].match(regex.section);
value[match[1]] = {};
section = match[1];
}else if(lines.length == 0 && section){//changed line to lines to fix bug.
section = null;
};
}
return value;
}
Based on the other responses i've modified it so you can have nested sections :)
function parseINI(data: string) {
let rgx = {
section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
param: /^\s*([^=]+?)\s*=\s*(.*?)\s*$/,
comment: /^\s*;.*$/
};
let result = {};
let lines = data.split(/[\r\n]+/);
let section = result;
lines.forEach(function (line) {
//comments
if (rgx.comment.test(line)) return;
//params
if (rgx.param.test(line)) {
let match = line.match(rgx.param);
section[match[1]] = match[2];
return;
}
//sections
if (rgx.section.test(line)) {
section = result
let match = line.match(rgx.section);
for (let subSection of match[1].split(".")) {
!section[subSection] && (section[subSection] = {});
section = section[subSection];
}
return;
}
});
return result;
}

scrape id from url using javascript

I have the following URL:
http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE%2527S%2BGARDEN.
Where bi is a identifier for the specific book.
How can I extract the book id from the link?
Thanks!
You can to use this regex:
var address = "http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&...";
var bi = /[\?&]bi=(\d+)/.exec(address)[1]
alert(bi)
function getBookId()
{
var query = document.location.split("?")[1];
var values = query.split("&");
for(var i = 0; i < values.length; i++)
{
a = values[i].split("=");
if(a[0] === "bi")
return a[1];
}
//some error occurred
return null;
}
You can extract the book id (assumed to be only numbers) via a regular expression (and grouping).
var s = "http://www.abebooks.com/servlet/BookDetailsPL?\
bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.\
%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE\
%2527S%2BGARDEN."
var re = /bi=([0-9]+)&/; // or equally: /bi=(\d+)&/
var match = re.exec(s);
match[1]; // => contains 1325819827
address.split("bi=")[1].split("&")[0]
Try this
var bookId
var matcher = location.search.match(/(?:[?&]bi=([^&]+))/); // Assuming window.location
if (null !== matcher) {
bookId = matcher[1];
}
I once had the same problem.
I created a little function to help me out. Don't know where it is but I managed to recreate it:
function get(item,url) {
if (url == undefined)
url = window.location.href;
var itemlen = item.length
var items = url.split('?')[1].split('&');
for (var i = 0, len = items.length;i<len;i++) {
if (items[i].substr(0,itemlen) == item)
return items[i].split('=')[1];
}
return null;
}
So you would use it like:
get('bi');
If the url you gave was your current url, if not you could do:
get('bi','http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE%2527S%2BGARDEN.')
Hope I didn't leave in any bugs :)

Categories

Resources