I'm trying to display only the odds from bet365 from a javacript piece of code. I can only think of doing this by searching for a part of the id of the bet, each bookie has its own related ids and bet365's is b3, so this query below I've tried to search for ids where the string includes the "b3" in it, as all other parts of it seem completely random
http://www.oddschecker.com/horse-racing/2015-06-30-chepstow/18:10/winner
var odds = document.getElementsByTagName("odds");
for (var i = 0; i < odds.length; i++) {
if(odds[i].id.indexOf("b3") == 0) {
odds[i].disabled = bDisabled;
}
}
Whenever I do this my return says undefined. How can I get this to work
It looks like the marker you're looking for is .co, from what I can see from the code (delimiting a td with the odds as inner content).
The site also has jQuery loaded up, so let's use jQuery to simplify the pseudo-code (we can always transform it to pure javascript later):
var odds = $('.co');
odds.each(function(){
var id = $(this).attr('id');
if(id.indexOf('_B3') >= 0){
console.log(id);
//your code here
}
});
Given that the ID is not at the end of the ID string, we can't check to see if the indexOf is == to 0; instead, we just want to know if the ID we're looking for (b3) is contained in that string. So we're looking for any value that is not -1, the value returned by indexOf when the query is not found in the original string.
I'm searching for specifically for _B3 for two reasons: One, indexOf is case sensitive, so given that your ID are uppercase, we must make our search uppercase too. I'm also adding the underscore in order to respect the ID string format, as I'm not 100% certain that your ID will only contain letters to delimit IDs from the bet vendor, so we can't be too safe with that.
In pure javascript:
var odds = document.getElementsByClassName('co');
for(var ii = 0; ii < odds.length; ii++){
if(odds[ii].id.indexOf("_B3") >= 0){
console.log(odds[ii].id);
//your code here
}
}
Related
I’m wondering how to solve a matching/lookup problem and I “think” a multi-dimensional array is the solution. In short, I want to match a list of comma separated SKUs stored as a cookie value against a finite list of SKUs with matching product names and print out the matched product names onto the page. I’m not sure if this is the best way to do this, but with what I have so far I’m not clear how to properly breakup the comma separated strings from the cookie (right now it’s trying to match the entire cookie value), match them to the matrix (17 total rows) and then print out the Product Name.
<script>
var staticList = [
[“1234”, “Chocolate Ice Cream”],
[“1235”, “Peanut Butter Cookie”],
[“6G2Y”, “Raspberry Jell-O”],
[“YY23”, “Vanilla Wafers”]
];
var cookieSkus = [‘1235,YY23’]; // comma separated value from cookie
jQuery(function () {
for (var i = 0; i < staticList.length; i++) {
if (cookieSkus.indexOf(staticList [i][0]) > -1) {
jQuery('#pdisplay).append(staticList [i] [1] + '<br />');
}
}
});
</script>
<p id=”pdisplay”></p>
In this example, the paragraph "pdisplay" would contain:
Peanut Butter Cookie
Vanilla Wafers
Is there a way to correct what I have above or is there a better method of accomplishing what I’m trying to do?
First, you might want to focus on the Cookie SKUs rather than the staticList. The reason for this is that the cookie may have a variable number, and may be as small as 0 elements. (After all, we don't need to list the items if there are no items).
This may be accomplished simply by converting the string to an array and then checking if the SKU is in the staticList. Unfortunately, since you are using a multidimensional array, this would require going through the staticList for each cookie sku. Using just this suggestion, here is a basic example and fiddle:
Rewrite: Accounting for the fact that staticList is an Array of Arrays
jQuery(function() {
var skus = cookieSkus[0].split(',');
for (var i = 0; i < skus.length; i++) {
for (var j = 0; j < staticList.length; j++) {
if (staticList[j][0] == skus[i]) {
jQuery('#pdisplay').append(staticList[j][2] + '<br/>');
break; // Will end inner if the item is found... Saves a lot of extra time.
}
}
}
});
Edit 2: Using an Object (A possibly better approach)
According to the comments, you must support IE8. In this case, you might consider an Object instead of a multi-dimensional array. The reasons for this are as follows:
An object is actually an associative array (with a few perks).
You can directly check for property existence without having any nested arrays.
Object property access is typically faster than looping through an array
You can access object properties nearly exactly like accessing an array's elements.
When using an Object, the original version of my code may be used without modification. This is because the object's structure is simpler. Here is a fiddle for you: option 2
var staticList = {
"1234": "Chocolate Ice Cream",
"1235": "Peanut Butter Cookie",
"6G2Y": "Raspberry Jell-O",
"YY23": "Vanilla Wafers"
};
jQuery(function() {
var skus = cookieSkus[0].split(',');
for (var i = 0; i < skus.length; i++) {
if (staticList[skus[i]])
jQuery('#pdisplay').append(staticList[skus[i]] + '<br/>');
}
});
Responding to your comment:
The reason that the output matches what is desired is because unlike an array which has numerical indices, the object's indices are the actual skus. So, there is no staticList[0] if staticList is an object. Instead (in the context of the staticList object), 1234 = "Chocolate Ice Cream". So, an object definition basically goes as follows:
var objectName = {
index1: value1,
index2: value2,
...,
...
}
The index may be any primitive value (integer or string). The value may be any valid javascript value including a function or an inner object. Now, to get the value at a specific index, you may do either:
objectName.index1 (no quotes)
OR:
objectName["index1"] (quotes needed if the index is a string)
The result of either of those will be:
value1
It's as simple as that.
I would try something like this:
var cookieSkus = cookieSkus[0].split(',');
staticList.filter(function(cell){
return cookieSkus.some(function(val){return cell[0] === val; });
}).map(function(cell){
jQuery('#pdisplay).append(cell[1] + '<br />');
});
Disclaimer: provided based on the sample code provided above along with recent comments
I have this part of code
<a href='project.php?id=5'>test</a>
Where id number can have different length and I need to extract only this number.
Is it possible through regular expression, or something better?
EDIT
I prob have solution, fitting my problem, what you think about:
string.split('=')[2].split('\'')[0]
When string contains text. I'm sure, that text will always have same pattern
Let's say you have your string "<a href='project.php?id=5'>test</a>"
Using regular expressions to parse HTML can get real ugly real fast (what if the a has more attributes? What if there are multiple tags there?)
The cleanest would be to dump it in a new HTML element and process it as HTML using the powerful native built in DOM API instead of as a string.
var temp = document.createElement("div");
temp.innerHTML = "<a href='project.php?id=5'>test</a>";
var url = temp.firstChild.href; // now contains project.php?id=5
Now we can use more traditional tools to extract the id
var id = url.split("=")[1]; // the first thing after =.
More generally the strategy is:
Create an empty element or a fragment and put our HTML there
Use DOM querying methods to find our elements, in this case .firstChild was enough but getElementsByTagName or even querySelector might be useful.
Once we got the attribute, it's just a simple string, and we can safely use regex for it, or any other string processing method we choose.
If you're unacquainted with the DOM API this tutorial is a good place to start. It's how we process the document with JavaScript and knowing it is important to your success as a front end JavaScript developer.
Fiddle
function parse(url){
var result = { pathname: null, search: {} };
var parts = url.split('?');
result.pathname = parts[0];
var search = parts[1];
if(search){
var ps = search.split('&');
for(var i = 0; i < ps.length; i++){
var p = ps[i].split('=');
result.search[p[0]] = p[1];
}
}
return result;
}
parse('project.php?id=5');
EDIT: To get anchor element:
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++){
var a = anchors[i];
if(a.innerHTML === 'test')
console.log(parse(a.href));
}
Was hoping someone may be able to point me in the right direction with this.
I have returned a list object in JSON format from .Net and then parse with JQuery.
var jsonOpens = $g.parseJSON(seriesReturn);
If I alert this I then receive the following:
1326531600000,8,49,1326531600000,8,49,1326535200000,11,169,1326535200000,11,169
What I then need to do with this is remove the second column.
I managed to do that by looping through and deleting
for (var i = 0; i < jsonOpens.length; i++) {
delete jsonOpens[i] [1];
}
This works but still leaves the column in place i.e alerts:
1326531600000,,49,1326531600000,,49,1326535200000,,169,1326535200000,,169
I tried doing a replace by replacing the double commas with single commas but this doesn't work in this format.
What would be the best way for me to identify a column and remove it completey whilst keeping the same format?
Assuming it's a JS array, you should be able to use the .splice() method to remove the appropriate elements:
http://www.w3schools.com/jsref/jsref_splice.asp
So, your loop would be (I think)
for (var i = 0; i < jsonOpens.length; i++) {
jsonOpens[i].splice(1,1);
}
I am looking to find the best possible way to find how many $ symbols are on a page. Is there a better method than reading document.body.innerHTML and calc how many $-as are on that?
Your question can be split into two parts:
How can we get the the webpage text content without HTML tags?
We can generalize the second question a bit.
How can we find the number of string occurrences in another string?
And the 'best possible way to do this':
Amaan got the idea right of finding the text, but lets take it further.
var text = document.body.innerText || document.body.textContent;
Adding textContent to the code helps us cover more browsers, since innerText is not supported by all of them.
The second part is a bit trickier. It all depends on the number of '$' symbol occurrences on the page.
For example, if we know for sure, that there is at least one occurrence of the symbol on the page we would use this code:
text.match(/\$/g).length;
Which performs a global regular expression match on the given string and counts the length of the returned array. It's pretty fast and concise.
On the other hand, if we're not sure if the symbol appears on the page at least once, we should modify the code to look like this:
if (match = text.match(/\$/g)) {
match.length;
}
This just checks the value returned by the match function and if it's null, does nothing.
I would recommend using the third option only when there is a large occurrence of the symbols in the page or you're going to perform the search many many times. This is a custom function (taken from here) to count the occurrence of the specified string in another string. It performs better than the other two, but is longer and harder to understand.
var occurrences = function(string, subString, allowOverlapping) {
string += "";
subString += "";
if (subString.length <= 0) return string.length + 1;
var n = 0,
pos = 0;
var step = (allowOverlapping) ? (1) : (subString.length);
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
n++;
pos += step;
} else break;
}
return (n);
};
occurrences(text, '$');
I'm also including a little jsfiddle 'benchmark' so you can compare these three different approaches yourself.
Also: No, there isn't a better way of doing this than just getting the body text and counting how many '$' symbols there are.
You should probably use document.body.innerText or document.body.textContent to avoid getting your HTML give you false positives.
Something like this should work:
document.body.innerText.match(/\$/g).length;
An alternate way I can think of, would be to use window.find like this:
var len = 0;
while(window.find('$') === true){
len++;
}
(This may be unreliable because it depends on where the user clicked last. It will work fine if you do it onload, before any user interaction.)
What I want to accomplish is simple. I want a button's text to change depending on what page your on.
I start this by using the following:
var loc_array = document.location.href.split('/');
Now that I have the url and split it in an array I can grab certain directories depending on the position, like so:
if (loc_array[loc_array.length-1] == 'stations'){
var newT = document.createTextNode("Stations & Maps");
}
Now this works if the directory is /test/stations/, however if someone types /test/stations/index.html then it doesn't work. How can you test against this without throwing in another if statement or using a similar conditional.
Actually both your examples work the same. /stations/ and /stations/index.html both get split into two strings; /stations/ has an empty string at the end. So length-2 would have worked. Where it wouldn't work would be /stations, which is up a level. But that wouldn't normally be an issue because if stations is a static directory, the web server will redirect the browser to /stations/ with the slash.
That won't happen if you're doing the routing yourself. If you're doing routing, it's not a good idea to index from the end of the list of path parts, are there might be any old rubbish there being passed as path-parameters, eg. /stations/region1/stationname2. In this case you should be indexing from the start instead.
If the application can be mounted on a path other than a root you will need to tell JavaScript the path of that root, so it can work out how many slashes to skip. You'll probably also need to tell it for other purposes, for example if it creates any images on the fly it'll need to know the root to work out the directory to get images from.
var BASE= '/path-to/mysite';
var BASELEVEL= BASE.split('/').length;
...
var pagename= location.pathname.split('/')[BASELEVEL];
// '/path-to/mysite/stations/something' -> 'stations'
I'm using location.pathname to extract only the path part of the URL, rather than trying to pick apart href with string or regex methods, which would fail for query strings and fragment identifiers with / in them.
(See also protocol, host, port, search, hash for the other parts of the URL.)
I don't think string splitting is the best approach here. I would do it using RegEx.
var reStations = /\/stations(\/)?/i;
if (reStations.test(document.location.href))
//Do whatever
Not sure exactly what you're looking for, see if this fits:
var loc_array = document.location.href.split('/');
// this will loop through all parts
foreach (var i in loc_array) {
switch (loc_array[i]) {
case "stations":
// do something
break;
// other cases
}
}
// or if you want to check each specific element
switch (loc_array[0]) {
case "stations": // assuming /stations/[something/]
if (typeof loc_array[1] != 'undefined' && loc_array[1] == "something") {
// do things
}
break;
}
if( document.location.href.split( "station" ).length > 1 ){
//...
}
I think I see where you are going with this... As someone stated above using a RegExp (regular expression) could be helpful... but ONLY if you had more than a single type of page to filter out (html/js/php/...), but for what it looks like you want to do. Try something like this:
var loc_array = document.location.href.split('/');
var i = loc_array.length-1;
var button_label = "default";
while(i>1)
{
//checks to see if the current element at index [i] is html
if(loc_array[i].indexOf(".html")>-1)
{
if(i>0)
{
var button_label = loc_array[i-1];
break;
}
}
i--;
}
alert(button_label);
What it does is:
capture the current URL(URI)
split it into an array
starting from the END of the array and working BACKWARDS, look for the first element that contains the ".html" file identifier.
We now know that the element BEFORE our current element contains the label we want to add to our buttons...
You can then take the value and assign it wherever you need it.
If you run out of elements, it has a default value you can use.
Not sure if this helps.....
I have tested the above code and it worked.
if (loc_array[4]=='stations')
if the url was http://www.example.com/test/stations/index.html, the values in the array would be:
[0] = "http:"
[1] = ""
[2] = "www.example.com"
[3] = "test"
[4] = "stations"
[5] = "index.html"
For simplicity's sake, supposing that there is an array of keywords (such as "station") that identify the pages, use a map and try to match its keys with the href string using indexOf,
var href = document.location.href ;
var identifiers = {
"station": "Stations & Maps" , //!! map keys to result strings
/* ... */
} ;
identifier_loop: //!! label to identify the current loop
for(var n in identifiers) { //!! iterate map keys
if( href.indexOf(n) !== -1 ) { //!! true if the key n in identifiers is in the href string
var newT = document.createTextNode( identifiers[n] ) ; //!! create new text node with the mapped result string
break identifier_loop ; //!! end iteration to stop spending ressources on the loop
}
}
Your example will show an empty string, cause the last item is empty; so you can simply make:
if (loc_array[loc_array.length-2] == 'stations')
{
var newT = document.createTextNode("Stations & Maps");
}