So here we have some url's from same domain:
http://example.com/video6757788/sometext
http://example.com/video24353/someothertext
http://example.com/video243537786/somedifferenttext
http://example.com/video759882
http://example.com/video64353415
http://example.com/video342432?session=somestring
How to get just the numbers part that comes after video in all types of the url's. I'm trying to get the video id's.
First i get the url's, but then how do I get the id's?
var url = $('a[href*="example"]');
var id = ???
Use a regular expression:
$('a[href*="example"]').each(function() {
var $this = $(this);
var url = $this.attr("href");
var id = url.match(/video(\d+)/i)[1]; //retrieve the number following video*
//logic
})
Or if you want to be fancy with .attr(), equivalent would be:
$('a[href*="example"]').attr("href", function(indx, url) {
var id = url.match(/video(\d+)/i)[1]; //retrieve the number following video*
//logic
})
Related
I am trying to look for data-reactid value and replace it with another value.
Here is the code:
Book a Room.
trying to use the code to replace ".0.2.2" with ".0.2.3"
(function () {
var link = document.querySelectorAll('a[data-reactid*=".0.2.2"]') //change example.com to any domain you want to target
var searchString = ".0.2.2" //the string to be searched forEach
var replacementString = ".0.2.3" //the replacement for the searched string
links.forEach(function(link){
var original = link.getAttribute("data-reactid");
var replace = original.replace(searchString,replacementString)
link.setAttribute("data-reactid",replace)
})
})();
Just change this
var link = document.querySelectorAll('a[data-reactid*=".0.2.2"]')
to this
var links = document.querySelectorAll('a[data-reactid*=".0.2.2"]')
But keep in mind that you should not change the attributes set by React itself
The javascript snippet that we have is :
Link
I would like to retrieve the value of data-test-socialmedia type. Based on that I would like to add the conditional statement to check if the data-test-socialmedia type is facebook. As we have many data attributes like this in the site.
I tried several ways and I get object as the value. But i need the actual value in this case it is facebook. Kindly help.
//first get element
var el = document.getElementsByClassName('n-contact')[0];
//get data and replace single quotes with double quotes to create valid JSON
var d = el.dataset.testSocialmedia.replace(/'/g, '"')
//parse JSON to javascript object
var parsed = JSON.parse(d, null)
//get country if type is facebook
if(parsed.options == 'facebook')
console.log(parsed.options.country)
Link
var str = document.querySelector('.n-contact').getAttribute('data-test-socialmedia').replace(/'/g,'"');
var obj = JSON.parse(str);
var result = obj.type;
console.log(result);
it would work.
With jQuery
var elementData = $(".n-contact").attr("data-test-socialmedia").replace(/'/g,'"'),
parsed = JSON.parse(elementData);
console.log(parsed);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Link
i try to get values of a url with anchor like this: http://website/list/#/genre/song
It is in jquery because after i get the values, i have to edit html tags contents.
I retrieve hash value with:
var hash = window.location.hash.substring(1);
I have 2 variables:
var genre;
var song;
the problem is that there may be 2 possibilities in the url:
http://website/list/#/genre or http://website/list/#/genre/
or
http://website/list/#/genre/song or http://website/list/#/genre/song/
if we are in case 1, i would have 'genre' value from hash variable
if we are in case 2, i would have 'genre' and 'song' values from hash variable
my jquery function is actually simple:
$(function(){
var hash = window.location.hash.substring(1);
var url_parts = hash.replace(/\/\s*$/,'').split('/');
console.log("result: "+url_parts);
});
I do not know how to consider the two cases. Actually i just get a full string.
And if i try http://website/list/#/genre/, the result is:
result: ,genre
can you help me?
Test whether a particular index exists after splitting:
$(function(){
var hash = window.location.hash.substring(1);
var url_parts = hash.replace(/\/\s*$/,'').split('/');
genre = url_parts.length >= 2 ? url_parts[1] : '';
song = url_parts.length >= 3 ? url_parts[2] : '';
console.log("result: "+url_parts);
});
I have a page which uses dropdowns to filter a listing. I have over 10 filters now and each of the change function, I am calling an AJAX request and passing corresponding variables to the PHP function. Like this :
$("#categories").change(function() {
uri = "myurl" ;
var status=$("#statusfilter").val();
var category=$("#categories").val();
var network=$("#networksfilter").val();
var prod_type = $("#prodtypefilter").val();
loadData(uri,category,status,network,prod_type);
});
and in loadData() I have the following code :
function loadData(uri,category,status,network,prod_type){
url + = category+"/"+status+"/"+network+"/"+prod_type;
$('#userdata').load(url);
}
Here I have given only 4 filters only, but it is actually 10 and may increase.Anyway this is working fine. But the problem is that as I increase the filters, I need to write this same for every dropdown change function. Is there any better approach to optimze the code and so I don't need to load a bunch of JS ?
Rename your filter elements' IDs to start with same word, for example "filter_". Then get all of them at once:
$('select[id^="filter_"]').change(function() {
var uri = "myurl";
var filters = new Array();
$('select[id^="filter_"]').map(function () {
filters[$(this).name()] = $(this).val(); // not tested, just an idea
});
loadData(uri,filters);
});
.map() iterates over its elements, invoking a function on each of them and recording the selected option value in the array.
You can use .each() if it's more intuitive from .map() for you:
$.each('select[id^="filter_"]', function() {
filters[$(this).name()] = $(this).val(); // not tested, just an idea
});
Note: It's a good idea to use associative array as #Tony noticed below to be sure which filter is for which database table attribute in your server side script.
You will need to write some code in any cases, but you can reduce it, for example like this:
$("#categories").change(function() {
uri = "myurl";
var filters = {
status: $("#statusfilter").val(),
category: $("#categories").val(),
network: $("#networksfilter").val(),
prod_type: $("#prodtypefilter").val()
}; // order is important
loadData(filters );
});
loadData(filters) {
var url = '';
for (var filterName in filters)
url += '/' + (filters[filterName] || 'any'); // here some def value needed
url = url.substring(1); // cut first slash
$('#userdata').load(url);
}
EDIT
Or even like this:
loadData(filters) {
var url = Object.keys(filters).map(function(el) {
return filters[el] || 'any';
}).join('/');
$('#userdata').load(url);
}
I want to replace a dynamic url query parameter with another parameter.
Eg. like my url is:
http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567&sc_cmp=pcp_GSF_Batteries+%26+Electrical+Accessories_209-0539
I want to replace everything starting after
&sc_cmp=pcp_GSF_Batteries+%26+Electrical+Accessories_209-0539
and add something like & new Static string
My final url should look like:
http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567& new static string.
Thanks
I recommend you to use the cool URI.js library, then it's as easy as:
var url = "http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567&sc_cmp=pcp_GSF_Batteries+%26+Electrical+Accessories_209-0539";
url = URI(url).removeSearch("sc_cmp").addSearch("newvar","newval");
// http://www.mysite.com/209-0539.prd?pageLevel=&skuId=111-4567&newvar=newval
alert(url);
See working demo .
If you don't want to include another library, following lets you add as many search items you want removed and add as many as you like without a lot of code
/* array of search keys to remove*/
var removeSearch = ['sc_cmp'];
/* array of new search items*/
var newSearchitem = ['image=cool'];
var url = location.href;
var pageUrl = url.split('?')[0];
var urlSearch = url.split('?')[1].split('&');
/* store search items in array */
var newSearchArr = [];
/* loop over exisiting search items and store keepers*/
for (i = 0; i < urlSearch.length; i++) {
var key = urlSearch[i].split('=')[0];
if ($.inArray(key, removeSearch) == -1) {
newSearchArr.push(urlSearch[i])
}
}
$.merge(newSearchArr, newSearchitem);
var newUrl = pageUrl + '?' + newSearchArr.join('&')
DEMO: http://jsfiddle.net/9VPUX/