Remove match word using jQuery - javascript

I want to split and join two type of url. For example
Url 1 :
http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC
Url 2 :
http://localhost/site/index.php?route=product/category&path=20&limit=8
<input type="hidden" class="sort" value="http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC" />
<input type="hidden" class="limit" value="http://localhost/site/index.php?route=product/category&path=20&limit=8" />
I'd like to join the query strings but remove duplicates.
I'm looking for this result at last
http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC&limit=8

var getUrlParameter = function getUrlParameter(sParam, url) {
var sPageURL = decodeURIComponent(url),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
Now read individual parametrs by
var order = getUrlParameter('order', 'http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC');
var limit = getUrlParameter('limit', 'http://localhost/site/index.php?route=product/category&path=20&limit=8');
and make a new url by using the parameters.

You could go with getting the query parameters in an array and de-duplicating them.
var url1 = "http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC";
var url2 = "http://localhost/site/index.php?route=product/category&path=20&limit=8";
var url = (url1.split`?`[1]+"&"+url2.split`?`[1]);
var result = url1.split`?`[0]+"?"+Array.from(new Set(url.split`&`)).join`&`;
console.log(result)
Note that you're left with order=ASC and order=DESC, of which only the last is processed. But looks like that's what you want...
For older browsers:
var url1 = "http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC";
var url2 = "http://localhost/site/index.php?route=product/category&path=20&limit=8";
var url = (url1.split('?')[1]+"&"+url2.split('?')[1]);
var result = url1.split('?')[0]+"?"+url.split('&').filter(function(x,i){
return url.split('&').indexOf(x) == i;
}).join('&');
console.log(result)

Related

Show <div> when a specific URL Parameter is met

I have a form in Google Sheets, which passes URL parameters to a page, which then should show content based on the URL parameters.
So if a person checks "item 1" and "item 2" in the Google Sheet, the parameter gets passed on as follows:
https://my-url.com/?item1=value1&item2=value2
Now there's several div containers, which are set to display:none with css. When the URL parameter is met, the hidden div container should show up. So the html is:
<div class="hidden" id="value1">This content should show, when the URL parameter value 1 is passed</div>
<div class="hidden" id="value2">This content should show, when the URL parameter value 2 is passed</div>
I've found some code online, which does pretty much that, but it can only display one div at a time: https://jennamolby.com/how-to-display-dynamic-content-on-a-page-using-url-parameters/
My problem is, that for every passed parameter, a field has to show.
Can anyone help me with this? I'm really not an expert in js by any means.
Good Luck
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var item1 = getParameterByName('item1');
var item2 = getParameterByName('item2');
if (item1 == "value1")
{
document.getElementById("value1").style.display = "block";
}
if (item2 == "value2")
{
document.getElementById("value2").style.display = "block";
}
.hidden
{
display: none;
}
<div class="hidden" id="value1">This content should show, when the URL parameter value 1 is passed</div>
<div class="hidden" id="value2">This content should show, when the URL parameter value 2 is passed</div>
You could do something like this:
$.each(getUrlVars(), function(i, x) {
$('#' + x).show();
})
function getUrlVars() {
var vars = {},
hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
//vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
getUrlVars is taken from this answer, and modified a bit.
Demo
var url = "https://my-url.com/?item1=value1&item2=value2"; //replace with window.location.href
$.each(getUrlVars(), function(i, x) {
$('#' + x).show();
})
function getUrlVars() {
var vars = {},
hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
//vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hidden" id="value1">This content should show, when the URL parameter value 1 is passed</div>
<div class="hidden" id="value2">This content should show, when the URL parameter value 2 is passed</div>
try this
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
let item1 = getUrlParameter('item1');
let item2 = getUrlParameter('item2');
if(item1 =='value1' &&item2 =='value2')
{
document.getElementById('showhide').style.display = 'block';
}
<div id="showhide" style="display: none">
hi hi
</div>

I need to get values from a url after (#) with jquery

I have this url:
http://test.words.aspx#word_id=1034374#lang_code=en
I need to get the values of word_id and Language code and assign them to variables.
var word_id = 1034374;
var lang_kod = en;
Here is the code you need:
var link = window.location;
var data = link.split("#");
var word_id = data[1].split("=")[1];
var lang_code = data[2].split("=")[1];
With window.location you get the url that you currently are (an alternative is document.location.
Then you split it by the hash symbol (link.split("#")) and the result is stored as an array of strings (data) which now contains http://test.words.aspx at index 0, word_id=1034374 at index 1 and lang_code=en at index 2;
What you have to do now is split the string at index 1 by the equals symbol (data[1].split("=")). This also is an array of string which has the word_id at index 0 and 1034374 at index 1 which is what you need (data[1].split("=")[1]).
Following the same logic you also get the lang_code variable.
Test it here:
var link = "http://test.words.aspx#word_id=1034374#lang_code=en"
var data = link.split("#");
var word_id = data[1].split("=")[1];
var lang_code = data[2].split("=")[1];
console.log("Word ID = " + word_id);
console.log("Lang Code = " + lang_code);
Hope this was helpful :)
You should really only have one URL fragment. But in your case you could do the following to achieve this.
var url = "http://test.words.aspx#word_id=1034374#lang_code=en"; // or use window.location;
var url_splitted = url.split('#');
alert((url_splitted[1]).split('=')[1]); // showing you the values
alert((url_splitted[2]).split('=')[1]); // showing you the values
var work_id = (url_splitted[1]).split('=')[1];
var lang_code = (url_splitted[2]).split('=')[1];
Working JSFiddle: https://jsfiddle.net/o0nwyvfz/
Note:
If you are about to use multiple URL fragments, I'd suggest you to use URL parameters e.g.: http://test.words.aspx?word_id=1034374&lang_code=en
Which you could retrieve by:
A solution provided by: http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
And this is how you can use this function assuming the URL is,
http://test.words.aspx?word_id=1034374&lang_code=en
var tech = getUrlParameter('word_id');
var blog = getUrlParameter('lang_code');

How to fetch urls in array from paragraphs in javascript

I want to fetch all urls available in paragraph or sentence in javascript in array. For example check paragraph below:
Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.
From above string, We have to get array of these two url.Solution 1: Solution 1, I know is to split paragraph with space, iterate over array and check for url one by one and push into url's array. But, It's a time taking solution.Are there better solution for finding it or above solution is fastest and good to go?Thank you.
Is this what you are looking for?
var list = [];
var sentence = "Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.";
var result = checkForURL(sentence);
function checkForURL(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function (url) {
return '<a>' + url + '</a>';
})
}
var number = result.split('<a>');
for (var i = 1; i < number.length; i++) {
list.push(number[i].split(".</a>")[0]);
}
alert(list);
You might want to split on :// to get a smaller array to iterate over.
Example:
Demo
JSFiddle
HTML
<p id='p'>
Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.
</p>
<h4>
URLs
</h4>
<ol id='results'>
</ol>
Javascript
findUrls();
function findUrls(){
var p = document.getElementById('p');
var res = document.getElementById('results');
var pStr = p.innerText;
var parts = pStr.split(/:\/\//);
if (parts.length < 2)
return;
for (var i = 1 ; i < parts.length ; i++){
var part = parts[i];
var lastPart = parts[i-1];
if (lastPart.length < 4 )
continue;
if (lastPart.length >= 4 && lastPart.substr(-4) == 'http')
part = 'http://' + part;
else if (lastPart.length >= 5 && lastPart.substr(-5) == 'https')
part = 'https://' + part;
var firstSpace = part.indexOf(' ');
if (firstSpace > -1)
part = part.substring(0, firstSpace);
var lastChar = part.charAt(part.length - 1);
if (lastChar == ',' || lastChar == '.' /* || ... */)
part = part.substring(0,part.length - 1);
res.innerHTML += '<li>' + part + '</li>'; // or push part to some result array
}
}
Try this approach. It might need some fine tuning..
var paragraphs = document.getElementsByTagName('p')
var regex = /(https?:\/\/.*?)(\s|$)/g;
var urls = [];
var badLastChars = [".", ","];
for (var i = 0; i < paragraphs.length; i++) {
var p = paragraphs[i].innerText;
var match;
while (match = regex.exec(p)) {
var url = match[1];
var lastChar = url[url.length-1];
if (badLastChars.indexOf(lastChar) > -1 ) {
url = url.slice(0,url.length-1);
}
console.log(url);
urls.push(url);
}
}
<p> Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.</p>
<p> Another paragraph https://stackexchange.com. and here is another url I am making up: https://mycoolurlexample.com/this/is/an/example</p>

How to get multiple named querystring values in jQuery/Javascript?

I've got the following parameters
/Search?category=1&attributes=169&attributes=172&attributes=174&search=all
I'm trying to get just the attributes querystring values as an array in javascript, for example.
attributes = ['169','172','174']
Bearing in mind there may be other parameters that are irrelevant such as search or category.
Might not the proper answer but just tried
var str = "/Search?category=1&attributes=169&attributes=172&attributes=174&search=all";
var str1 = str.split("&");
var attributesArray = [];
for(var i=0; i<str1.length; i++) {
if (str1[i].includes("attributes")) {
attributesArray.push(str1[i].replace("attributes=", ""));
}
}
Fiddle https://jsfiddle.net/5Lkk0gnz/
You can do it like this:
(function() {
function getJsonFromUrl(url) {
var query = url.substr(1);
var arr = [];
query.split("&").forEach(function(part) {
var item = part.split("=");
arr.push(decodeURIComponent(item[1]));
});
return arr;
}
var url = "https://example.com?category=1&attributes=169&attributes=172&attributes=174&search=all";
var params = getJsonFromUrl(url);
console.log(params);
})();
Hope this helps!
This should do what you want, assuming you already have your url:
var url = "/Search?ategory=1&attributes=169&attributes=172&attributes=174&search=all";
var attrs = url
.match(/attributes=\d*/g)
.map(function(attr){
return Number(attr.replace("attributes=", ""));
});
console.log(attrs); //=> [169, 172, 174]

How to get the value of an id from the url-jquery

url: testPage?id=67346756384/indexList
how to get the location of the id from the above url? I tried this:
getIdLocation = $(location).attr("href");
id = getIdLocation.substring(getIdLocation.lastIndexOf("/") + 1);
but that gets me "indexList". I need the id.Any ideas??
Thanks!
I have used this function, it works great.
It will be something like this for your case, pretty simple:
var id = GetURLParameter('id');
Full code from the link:
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];
}
}
}​
Although, I prefer to pass the url as a parameter. It will be easier to write unit tests for that.
Use the first and second parameters of substr to designate the start and length of the string to be extracted:
var id = str.substring(str.lastIndexOf("=")+1,str.lastIndexOf("/"));

Categories

Resources