I'm trying to write a userscript for a game I'm playing. It uses this piece of HTML code:
<td valign="center">
<b>ten-leaf clover</b>
(4 left in stock for today)
</td>
This is a picture of what we're talking about:
The script should search for a string containing the words "left in stock for today", then look for an integer within this string. (The '4' is not constant, it changes every day.) Lastly, I would like to store this integer as a variable, so I can replace the '1' in the input field. Like this:
var clover = EnterCodeHere
$("input.text[name='quantity']").val(clover);
You can used a regex like so:
var textToSearch = $("td").innerHtml(); //You'll need a better selector than this. better to use a class or id
var clover = parseInt(textToSearch.match(/\d+\s*left in stock for today/)[0].match(/\d+/)[0]);
$("input.text[name='quantity']").val(clover);
You may want to check the array isn't empty before just taking the first value but if your confident it'll be there should be grand.
Related
So lets say I have a mailto email in which a checkbox question exists that asks the user to pick the best fruits out of a list of fruits (check all that apply.) They end up with apples, bananas, and pears. The mailto email that they trigger then contains the following (assuming the checkboxes in the question are named bestFruits):
...
bestFruits=apples
bestFruits=bananas
bestFruits=pears
...
So in my javascript file, I have the following line to parse values from the email:
var bestFruits = mail.bodyText.match(/bestFruits=\s*(\S.*\S)\s*/);
So my issue is that this would (presumably) take only one value by the end. What I need, is for the javascript to loop and add each value of bestFruits in the email to the bestFruits var so that each value (apples, bananas, and pears) are all in the bestFruits var.
Is there any way to do this? I tried making a for loop, but I couldn't determine the syntax to loop through the mailto email body and add each instance of bestFruits to the variable.
I'm still extremely new to all this, as I was thrust in recently. If I'm missing something fundamental, I'd appreciate a quick pointing-out. If you require any more info, I'd be happy to try to provide it.
Thanks for reading guys!
You don't need looping. You do need to match all the fruits (as per your example, matching all single words after bestFruits), remove bestFruits= from the matches, join the resulting array and store it in a variable. Like this:
var bestFruits = mail.bodyText.match(/bestFruits=\w+/g)
.map(function(x){return x.split('=')[1]})
.join(',');
What does it do:
Matches all your best fruits.
Takes each bestFruits=abc element and replaces it with abc (i.e., splits with = separator and takes the second part)
Makes the string of your fruits (converts the resulting array to string with , joiner).
You were very close - modified your regex a little bit:
var body = `this=is
an=example
bestFruits=apples
bestFruits=bananas
bestFruits=pears
of=doing
things=ok?
`;
var re = /bestFruits=(.*)/g;
var fruitMatches = body.match(re);
var bestFruits = fruitMatches.map(function(fruitMatch) {
return fruitMatch.split('=')[1];
});
console.log(bestFruits); // ["apples", "bananas", "pears"]
Fiddle
I have a string:
Name1<br/>Name2<br/>Name3
Im looking to get a choice selector or an array with just the Names as values. I know you can get just the text of a string, but I cant figure out a way separate them. This list changes so I cant hard code the names in.
I cannot find any code nor do I have anything yet.
Use the split function:
var text = "Name1<br/>Name2<br/>Name3";
var list = text.split("<br/>");
This is easily accomplished using JavaScript built-in split().
var input_s = "Name1<br />Name2<br />Name3";
var input_r = input_s.split("<br />");
I'm trying to do something very simple, but I can't get to work the way I intend. I'm sure it's doing exactly what I'm asking it to do, but I'm failing to understand the syntax.
Part 1:
In the following example, I want to extract the part of the string between geotech and Input.
x = "geotechCITYInput"
x.match(/^geotech(.*)(?:Input|List)$/)
The result:
["geotechCITYInput", "CITY"]
I've been writing regex for many years in perl/python and even javascript, but I've never seen the ?: syntax, which, I think, is what I'm supposed to use here.
Part 2:
The higher level problem I'm trying to solve is more complicated. I have a form with many elements defined as either geotechXXXXInput or geotechXXXXList. I want to create an array of XXXX values, but only if the name ends with Input.
Example form definition:
obj0.name = "geotechCITYInput"
obj1.name = "geotechCITYList"
obj2.name = "geotechSTATEInput"
obj3.name = "geotechSTATEList"
I ultimately want an array like this:
["CITY","STATE"]
I can iterate over the form objects easily with an API call, but I can't figure out how to write the regex to match the ones I want. This is what I have right now, but it doesn't work.
geotechForm.forEachItem(function(name) {
if(name.match(/Input$/)
inputFieldNames.push( name.match(/^geotech(.*)Input$/) );
});
Any suggestions would be greatly appreciated.
You were missing the Input and List suffix in your regex. This will match if the name starts with geotech and ends with either Input or List and it will return an array with the text in the middle as the second item in the array.
geotechForm.forEachItem(function (name) {
var match = name.match(/^geotech(.*)(Input|List)$/);
if (match) {
inputFieldNames.push(match[1]);
}
});
I have a table element :
<td class="commision_value">£ 40.89</td>
Now i want to get the float value of this td using jquery
So i do
alert(parseFloat($(".commision_value").text()));
but it returns NaN instead of 40.89.
can some one tell me the problem ?
A almost reliable solution would be to use a regex to get the number part :
var value = parseFloat($(".commision_value").text().match(/[\d\.]+/)[0]);
But depending on the context, especially if the formatting can change (some units are placed after the value, some number formattings involve spaces, etc.), it would be cleaner to add the value in a data attribute :
<td class="commision_value" data-value="40.89">£ 40.89</td>
var value = $(".commision_value").data('value');
The better solution here is to store the raw number in an attribute when you build the element in the first place:
<td class="commision_value" data-value="40.89">£ 40.89</td>
Then, when you want to read it there's no need to parse out the pound sign, or anything else
alert($(".commision_value").data('value'));
Remove the pound and anything else that is not a number or . or ,
alert(parseFloat($("#test").text().replace(/[^\d.,]/g,'')));
Ok, I'm a bit of a n00b when it comes to JS (I'm not the greatest programmer) so please be gentle - specially if my questions been asked already somewhere and I'm too stupid to find the right answer. Self deprecation out of the way, let's get to the question.
Problem
There is a site me and a large group of friends frequently use which doesn't display all the information we may like to know - in this case an airline bookings site and the class of travel.
While the information is buried in the code of the page, it isn't displayed anywhere to the user.
Using a Greasemonkey script, I'd like to liberate this piece of information and display it in a suitable format.
Here's the psuedocode of what I'm looking to do.
Search dom for specified element
define variables
Find a string of text
If found
Set result to a variable
Write contents to page at a specific location (before a specified div)
If not found
Do nothing
I think I've achieved most of it so far, except for the key bits of:
Searching for the string: The page needs to search for the following piece of text in the page HEAD:
mileageRequest += "&CLASSES=S,S-S,S-S";
The Content I need to extract and store is between the second equals (=) sign and the last comma ("). The contents of this area can be any letter between A-Z.
I'm not fussed about splitting it up into an array so I could use the elements individually at this stage.
Writing the result to a location: Taking that found piece of text and writing it to another location.
Code so far
This is what I've come up so far, with bits missing highlighted.
buttons = document.getElementById('buttons');
''Search goes here
var flightClasses = document.createElement("div");
flightClasses.innerHTML = '<div id="flightClasses"> ' +
'<h2>Travel classes</h2>' +
'For the above segments, your flight classes are as follows:' +
'write result here' +
'</div>';
main.parentNode.insertBefore(flightClasses, buttons);
If anyone could help me, or point me in the right direction to finish this off I'd appreciate it.
The Content I need to extract and store is between the second equals (=) sign and the last comma (").
Do you mean "is between the second equals (=) sign and the last quote (")"?
And I assume that this:
mileageRequest += "&CLASSES=S,S-S,S-S";
is in a script tag?
If so then it looks like there will be a JS variable on the page called mileageRequest which you can access from Greasemonkey with unsafeWindow.mileageRequest and assuming that you can access the data you want with something like:
// check that the mileageRequest variable exists
if(unsafeWindow.mileageRequest){
// it exists
var myString = unsafeWindow.mileageRequest.match(/&CLASSES=([^&=]*)/i);
if(myString){
// my string exists
myString = myString[1];
}
else{
// my sting does not exist
}
}
else {
// it does not exist
}
or you can try:
var myString = document.getElementsByTagName('head')[0].innerHTML.match(/mileageRequest\s*\+=\s*"&CLASSES=([^"]*)";/i);
if(myString){
// my string exists
myString = myString[1];
}
else{
// my string does not exist
}