Remove part of the link in javascript - javascript

I want to create a button were people can click on to get redirected to a new url based on the current url.
/collection/?filter_kleur=grijs&query_type_kleur=or
I want everything after collection/ to be removed. What is the easiest way to fix this?

You could use the URL api.
const url = new URL('https://test.be/collection/?filter_kleur=grijs&query_type_kleur=or');
const output = document.getElementById('output');
output.innerHTML = url.host + url.pathname;
<output id="output"></output>

Related

Basic website that simply shows query string

I am trying to do the following: We need an easy way for user to find out what "id" their system has for remote support for example. I want to create a shortcut on everyone's desktop that leads to a website which then shows them their id with a query string (?id=..).
For example: the shortcut to https://example.com/support/index.html?id=80085 should open up a website which then shows "Your ID is 80085, please contact +1 123 456 for support or visit our online help page"
I am able to do all of that in html except showing the id in the body of the website
Does anyone have an example how I could do something like this?
If I understand what you are trying to do, basically I would create an HTML page with a simple div with an ID (for it to be found in script), and create a script that manipulates the url and places the corresponding text in the page.
...
<body>
<div id="main-div"></div>
<script>
const div = document.getElementById('main-div');
const element = document.createElement('p');
const id = new URLSearchParams(window.location.search).get('id');
if (!id) {
const emptyIdText = document.createTextNode('There was an error');
element.appendChild(emptyIdText);
} else {
const idText = document.createTextNode('Your ID is ' + id + ', please contact +1 123 456 for support or visit our online help page');
element.appendChild(idText);
}
div.appendChild(element);
</script>
</body>
...
If you need, you can place this script in a .js file and import it via the src attribute of the script tag. Hope this helps!
You can get the id parameter by converting the current url to a URL object in JavaScript like so
// get the current url
const url = new URL(window.location.href)
// extract the id parameter from the url
const id = url.searchParams.get('id')
// print the results to the screen
console.log(`Your ID is ${id} please call ...`)

How to Get 10 from this link (https://google.com/?ib=10)

Check this image
I have this link in (note this link not from search URL)
var link = https://google.com/?ib=10 in main.js file.
Now how to get that 10 from this link in javaScript on Page load
I have tried this way
var link1 = link;
const url3 = new URLSearchParams(link1);
const ur = url3.get("ib");
var finaltgid = ur;
alert(ur);
But its not working may be this code only work when we use window.location.search
Instead of var or const
urlsearchparams does not parse full url, you need to pass only query part, like this:
var link = 'https://google.com/?ib=10';
const url = new URLSearchParams(new URL(link).search);
const ib = url.get("ib");
console.log(ib);
URLSearchParams only accepts the actual query part in the constructor. You are including the full link.
Edit: For a given link you can just supply the link in place of document.location (which directly fetches the pages current location)
Considering this as Vanilla JS. You can do the following.
let params = (new URL(document.location)).searchParams;
let ib = parseInt(params.get('ib')); // is the number 10
Note, using the parseInt to get the value as a number.

Get current URL and add something in front with JavaScript

For a multi-language website, I want two buttons for the two languages that exist on the website.
The standard url would be: mydomain.com/something (this would be in german for example) The english url for this is: mydomain.com/en/something
How can I set up the buttons to get the current url/ page (in this case /something and add /en in front of it? Everything I found was to add stuff after the full domain.
Thank you very much.
check Location Obj MDM docs
console.log(document.location.origin + "/en" + document.location.pathname)
I'm not sure what your end goal is but if it involves reloading the same page with the localisation in the URL (i.e. on button click the page reloads and the page's URL is changed to mydomain.com/en/something meaning that on your next button click, the page would need to reload and its URL would need to be mydomain.com/something again) then you may need to look into RegEx and running it against the current URL to then swap out the URLs in the button so that on click you go to the correct version of the domain.
If the end goal is to only get the current URL and toggle whether the localisation appears in the URL or not then take a look at the snippet below which should hopefully help you out a bit.
For some further reading, I think these resources may be helpful for you:
RegEx: Regular expressions guide
RegEx: Regex101 - this is essentially a playground for practicing and testing your RegEx.
Location Object: MDN or W3Schools
jQuery(document).ready(function($) {
var $languageToggle = $('#language-toggle');
var origin = location.origin;
var pathname = location.pathname;
$languageToggle.on('click', function() {
var $this = $(this);
var toLanguage = $this.data('to-language');
var currentLanguage = $this.data('current-language');
var localisation = '';
/**
* This if statement will help prevent the constructedUrl variable
* from ever having a url such as https://website.com//page
* (notice the double forward slashes after .com).
*/
if (toLanguage) {
localisation = '/' + toLanguage;
}
var constructedUrl = origin + localisation + pathname;
$this.data('to-language', currentLanguage);
$this.data('current-language', toLanguage);
$('#output').text(constructedUrl);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">Click on the toggle button</div>
<button id="language-toggle" data-to-language="en" data-current-language="">
Toggle language
</button>
var myFunc = () => {
window.location.href = window.location.href + "place you text here"
}
Click the button and the page will be edited
<button onclick="myFunc()">click me</button>

Catching a param from URL by using Node.js

I have a constant link looking like this:
http://link.com/?val1=val1&val2=val2
And this link redirects me to a new link with a random value of a constant param such like;
http://link2.com/?constant=randomvalue/
Each time I use the first link, I get a random value from the following link.
By using Node.js, how can I catch the 'randomvalue' of 'constant' in the second link?
I have to use the first link to reach the second one.
Try reading the second link as a URL
let secondURL = new URL("http://link2.com/?constant=randomvalue/");
Then extract the value of the constant searchparam like so
let constantValue = secondURL.searchParams.get("constant"); //"randomvalue/"
#Misantorp's answer is probably best, but there is another way to do it. Check out the querystring module built into Node, it has a convenient parse method just for things like this: https://nodejs.org/api/querystring.html
This should work:
const querystring = require('querystring');
querystring.parse("http://link2.com/?constant=randomvalue/"); // { 'http://link2.com/?constant': 'randomvalue/' }
You may want to substring from the ? onwards to make it more clear:
const str = "http://link2.com/?constant=randomvalue/";
const paramIndex = str.indexOf("?");
if (paramIndex >= 0) {
const queryParamStr = str.substr(str.indexOf("?"));
const queryParams = querystring.parse(queryParamStr);
console.log(queryParams["constant"]);
}

how to delete a part of urls using javascript

I wanna know how to delete a part of urls using javascript
here's an example :
1.bp.blogspot.com/-gAOB6nWGgT0/Vtmbryn-e-I/AAAAAAAAWG0/jE5iiKmzi0Q/**s72**-c/imga0343.jpg
2.bp.blogspot.com/-zO5IrZEk-ck/VthrVoL0H4I/AAAAAAAARBw/LvQFWENcVB0/**s72**-c/s7e.jpg
3.bp.blogspot.com/-dfwIePlSYWw/Vtl5w0YqmBI/AAAAAAAARC8/BOeebRHZWzA/**s72**-c/facema.jpg
I wanna delete this part of urls :**s72**
I don't know what you scenario is, but If you just want to delete the s72 from the url and use it elsewhere, it's as easy as
javascript:
var url = window.location.href;
var newUrl = url.replace(/\/s72-/, "/-");
//then if you want to navigate to the new url,
window.location.href = newUrl;

Categories

Resources