Extract string html with regex on interval - javascript

There is a public website with this in the source:
</div><script type="text/rocketscript">
function calculateIndexIncome() {
var khs = $('#t9').val();
var btcusd = $('#t9_1').val();
var btckhs = $('#t9_2').val();
var dayprofitperkhs = 0.00000018188885404454654
var arr = btcusd.split(' ');
btcusd = arr[0];
var totalinvestmentusd = ((khs * btckhs) * btcusd).toFixed(2);
var totalinvestmentbtc = (khs * btckhs).toFixed(8);
var dailyincomebtc = (khs * dayprofitperkhs).toFixed(8);
var dailyincomeusd = ((khs * dayprofitperkhs) * btcusd).toFixed(2);
var monthlyincomebtc = (dailyincomebtc * 31).toFixed(8);
var monthlyincomeusd = (dailyincomeusd * 31).toFixed(2);
var breakevendays = (totalinvestmentusd / dailyincomeusd).toFixed(0);
var monthlypercentage = ((100 / breakevendays) * 30).toFixed(2);
$('#tl').html('Total KHS: ' + khs + '<br/>Total Investment: ' + totalinvestmentbtc + ' BTC ($' + totalinvestmentusd + ' USD)<br/><br/>Daily Income: ' + dailyincomebtc + ' BTC ($' + dailyincomeusd + ' USD)<br/>Monthly Income: ' + monthlyincomebtc + ' BTC ($' + monthlyincomeusd + ' USD)<br/><br/>Break Even In: ' + breakevendays + ' Days.<br/><br/>Monthly Rate: ' + monthlypercentage + '%');
}
I need to be able to extract two values: btckhs and dayprofitperkhs.
if I look at page source, dayprofitperkhs is different everytime I refresh.
Edit:
Jimmy Chandra came up with this bookmarklet:
javascript:
setInterval(logging,60000);
w1 = window.open("https://scrypt.cc/index.php");
function logging(){
console.log (w1.$('#t9_2').val());
var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;
var matches=re.exec(document.body.innerHTML);
console.log(RegExp.$1);
w1.location.href = 'https://scrypt.cc/index.php';
}
This works ALMOST perfectly. it gets the dayprofitperkhs, but only on the first interval.
After that, the value is no longer updated, although t9_2 IS updated...
Anyone?

I don't know where that site is, so I am just running this against this SO question, but the following bookmarklet is getting me what I want...
As I mentioned in the comment, I use Regular Expression against the document body inner html and I am looking for dayprofitperkhs and capturing the numbers and decimal separator on the right side of the equal sign. Also trying to compensate for any extra spaces in between (\s*). RegExp.$1 gave me the number that I am looking for.
javascript:(function(){var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;var matches=re.exec(document.body.innerHTML);console.log(RegExp.$1);}());
So your final bookmarklet should be something like:
javascript:
setInterval(logging,60000);
w1 = window.open("siteurl.com");
function logging(){
console.log (w1.$('#t9_2').val());
var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;
var matches=re.exec(w1.document.body.innerHTML);
console.log(RegExp.$1);
w1.location.href = 'siteurl.com';
}

The variables in question are local variables within the calculateIndexIncome() function, so no, you can't access them from outside that function.
The reason the first one "works" is because you're not referring to the variable, but rather the value: $('#t9_2').val(). This is a jquery selector which finds the element with the ID t9_2 and grabs its value.

You cannot visit it because its a local variable, it only exists in calculateIndexIncome() function.
By the way, you needn't open a new window to visit the variables. You can use chrome dev tools to directly modify the javascript to print the values, or set a breakpoint to debug the code.
Here is a tutorial for chrome dev tools: https://www.codeschool.com/courses/discover-devtools

Related

Unexpected Number error

I have been writing a function to allow users to upload images from their local file system to a website using JavaScript. I have successfully been able to upload images to the browser.
I have also written a function to allow the user to delete these images.
var count = 0;
function getPhoto(){
var file = document.getElementById('ad_photo');
var list = document.getElementById('ad_photo_upload');
var fReader = new FileReader();
var photo_list = [];
var counter;
fReader.readAsDataURL(file.files[0]);
fReader.onloadend = function(event){
counter = count.toString();
list.innerHTML += "<li id = 'pic " + counter + "'><img src='" + event.target.result + "'></img><a class = 'close' onclick = 'rem_pic(pic " + counter + ")'>X</a></li>";
photo_list[count] = event.target.result;
count++;
}
}
function rem_pic(theID){
var element = document.getElementById(theID);
element.outerHTML = "";
delete element;
}
My issue is whenever I call the "rem_pic(theID)" function I get a Chrome Browser error message that says "Uncaught SyntaxError: Unexpected number". Does anyone have any clue to why this might be? And how I could possibly improve the functions I have written so they work correctly?
Thanks
This happens because you pass a number to your function:
'rem_pic(pic " + counter + ")'
will render to
'rem_pic(pic 1)'
^ or any other number according to your counter value
And this is wrong as javascript params can't contain spaces.
So you probably need to pass a string:
rem_pic(\"pic " + counter + "\")
Looking at your code seems like you use it's as HTML id attribute. id attribute can't contain space chars too so your code should be like
rem_pic(\"pic" + counter + "\")
if your id in layout has format id="pic1", id="pic2", etc.

In Qualtrics surveys, how can you use JavaScript to dynamically set the range of a slider?

I was making a survey in Qualtrics, and needed to have my items show different values of the slider depending on a variable, in my case, the value from a loop and merge. That didn't seem like a thing that you could do with piped text, so I had to figure out how to do it in Javascript.
I'm just posting this as an opportunity to provide the answer I found on my own. As usual with Qualtrics, your mileage may vary, and this may need to be modified for your specific situation. In particular, the question IDs and postTags change depending on whether it is in a loop/merge, and perhaps on other factors.
Put the following code into the javascript section of the question:
// Set the slider range
// First define the function to do it
setSliderRange = function (theQuestionInfo, maxValue) {
var postTag = theQuestionInfo.postTag
var QID=theQuestionInfo.QuestionID
// QID should be like "QID421"
// but postTag might be something like "5_QID421" sometimes
// or, it might not exist, so play around a bit.
var sliderName='CS_' + postTag
window[sliderName].maxValue=maxValue
// now do the ticks. first get the number of ticks by counting the table that contains them
var numTicks = document.getElementsByClassName('LabelDescriptionsContainer')[0].colSpan
// do the ticks one at a time
for (var i=1; i<=numTicks; i++) {
var tickHeader='header~' + QID + '~G' + i
// the first item of the table contains the minimum value, and also the first tick.
// so we do some tricks to separate them out in that case.
var tickSpanArray = $(tickHeader).down("span.TickContainer").children
var tickSpanArrayLength=tickSpanArray.length
var lastTickIndex=tickSpanArrayLength - 1
var currentTickValue = tickSpanArray[lastTickIndex].innerHTML
currentTickValue=currentTickValue.replace(/^\s+|\s+$/g,'')
console.log('Tick value ' + i + ' is ' + currentTickValue)
// now get the new value for the tick
console.log('maxValue: ' + maxValue + ' numTicks: ' + numTicks + ' i: ' + i)
var newTickValue = maxValue * i / numTicks //the total number of ticks
tickSpanArray[lastTickIndex].innerHTML=newTickValue.toString()
console.log('Changed tick value to ' + newTickValue)
}
}
var currentQuestionInfo = this.getQuestionInfo()
var currentQuestionID = currentQuestionInfo.QuestionID
// Now call the function
setSliderRange(currentQuestionInfo, theMaxValueYouWant)
If you find my answers helpful, help raise my reputation enough to add "qualtrics" as a valid tag!! Or, if someone else with reputation over 1500 is willing to do it that would be very helpful!

Create variable from array keys in JavaScript

Is there a way to make a variable using an array value? For ex.
//Define all Notes in Sharps and Flats
var noteSharp = ["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"];
var noteFlat = ["A","Bb","B","C","Db","D","Eb","E","F","Gb","G","Ab"];
//Make all Major Scales
for (var x=0; x<12; x++){
var noteSharp[x] + "Sharp" = noteSharp[x] + noteSharp[x+2] + noteSharp[x+4] + noteSharp[x+5] + noteSharp[x+7] + noteSharp[x+9] + noteSharp[x+11];
var noteFlat[x] + "Flat" = noteFlat[x] + noteFlat[x+2] + noteFlat[x+4] + noteFlat[x+5] + noteFlat[x+7] + noteFlat[x+9] + noteFlat[x+11];
}
If I do a console.log(CSharp) it says that CSharp is not defined.
In this example I am trying to define a total of 24 variables. Some variable name examples im expecting to get are ASharp , A#Sharp , BbFlat , DFlat. The CSharp and CFlat variable should both be "CDEFGAB"
If this is not possible is it because variables have to be defined before the javascript file is read by the browser at run-time for memory leak security.
If you want to make a global variable, attach it to window
window[variableNameHere] = itsValue;
In your case:
window[noteSharp[x] + "Sharp"] = noteSharp[x] + ...
But it's not good to pollute the global namespace. How about putting it in another namespace:
var sharps = {};
var flats = {};
sharps[noteSharp[x] + "Sharp"] = noteSharp[x]...
flats[noteFlat[x] + "Sharp"] = noteFlat[x]...
//access them
sharps.ASharp;
I quite can't figure out what your code does, but this solution should point you to the right direction.
try the following code
var noteSharp = ["A","B","C"];
for(i in noteSharp) {
window[noteSharp[i]] = 'value of '+noteSharp[i];
}
alert(A)
alert(B)
alert(C)
This is exactly what you want.
and rewriting it for your code
//Define all Notes in Sharps and Flats
var noteSharp = ["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"];
var noteFlat = ["A","Bb","B","C","Db","D","Eb","E","F","Gb","G","Ab"];
//Make all Major Scales
for (var x=0; x<12; x++){
window[noteSharp[x] + "Sharp"] = noteSharp[x] + noteSharp[x+2] + noteSharp[x+4] + noteSharp[x+5] + noteSharp[x+7] + noteSharp[x+9] + noteSharp[x+11];
window[noteFlat[x] + "Flat"] = noteFlat[x] + noteFlat[x+2] + noteFlat[x+4] + noteFlat[x+5] + noteFlat[x+7] + noteFlat[x+9] + noteFlat[x+11];
}
alert(ASharp);
alert(AFlat);
As per my knowledge, in JavaScript there are 2 ways by which you can create dynamic variables:
eval Function
window object
eval:
var times = 1;
eval("var sum" + times + "=10;");
alert(sum1);
window object:
var times = 1;
window["sum" + times] = 10;
alert(window["sum1"]);
Change the end of your code to look like this:
for (var x=0; x<12; x++){
self[noteSharp[x] + "Sharp"] = noteSharp[x] + noteSharp[x+2] + noteSharp[x+4] + noteSharp[x+5] + noteSharp[x+7] + noteSharp[x+9] + noteSharp[x+11];
self[noteFlat[x] + "Flat"] = noteFlat[x] + noteFlat[x+2] + noteFlat[x+4] + noteFlat[x+5] + noteFlat[x+7] + noteFlat[x+9] + noteFlat[x+11];
}
As a result, you will have global variables with variable names like you want, such as CSharp, which would equal "CDEFGAB"--however, complicated variable names like A#Sharp cannot be written outright as variables, but can still be accessed by using subscript notation, like this self["A#Sharp"] (or window["A#Sharp"] in most cases, although it has traditionally been better style to use self rather than window to refer to the most local window object connected with a script instance).
The other answer looks like it has been finished out by the time I finished typing mine, and it looks good, too.
If this is not possible
It isn't for local variables without the use of eval.
is it because variables have to be defined before the javascript file is read by the browser at run-time for memory leak security.
No. It's not possible because ECMA-262 specifies that the only way to declare a variable is by a variable declaration statement, which is of the form:
var *identifier* [optional initialiser]
where identifier is a valid identifier, which can't be an expression like:
var 'foo' + 'bar';
The rest of the question has been covered in other answers.

Updating a ScriptProperty to avoid retrieving duplicate Twitter statuses

I was interested in writing a twitter bot to help out some friends at a local ski resort. I found this tutorial from Amit Agarwal which gave me enough to get started (it did take me more than 5 minutes since I did a lot of modifying). I host the script on google docs.
FIRST I think this is javascript (my understanding is that google apps script uses javascript...) and when I have had problems with the code so far, google searches for javascript-such-and-such have been helpful, but if this is not actually javascript, please let me know so I can update the tag accordingly!
I have no prior experience with javascript, so I am pretty happy that it's actually working. But I want to see if I'm doing this right.
The start function initiates the trigger, which kicks off the fetchTweets() function every interval (30 minutes). In order to avoid duplicates (the first errors I encountered) & potentially being flagged as spam, I needed a way to ensure that I was not posting the same tweets over and over again. Within the start() function, the initial since_id value is assigned:
ScriptProperties.setProperty("SINCE_TWITTER_ID", "404251049889759234");
Within the fetchTweet() function, I think I am updating this property with the statement:
ScriptProperties.setProperty("SINCE_TWITTER_ID", lastID + '\n');
Is this a good way to do this? Or is there a better/more reliable way? And if so, how can I be sure it's updating the property? (I can check the log file and it seems to be doing it, so I probably just need to create a permanent text file for the logger).
Any help is greatly appreciated!!
/** A S I M P L E T W I T T E R B O T **/
/** ======================================= **/
/** Written by Amit Agarwal #labnol on 03/08/2013 **/
/** Modified by David Zemens #agnarchy on 11/21/2013 **/
/** Tutorial link: http://www.labnol.org/?p=27902 **/
/** Live demo at http://twitter.com/DearAssistant **/
/** Last updated on 09/07/2013 - Twitter API Fix **/
function start() {
Logger.log("start!" + '\n')
// REPLACE THESE DUMMY VALUES
// https://script.google.com/macros/d/18DGYaa-jbaAK9rEv0HZ2cMcWjFGgkvVcvr6TfksMNbbu2Brk3gZeZ46R/edit
var TWITTER_CONSUMER_KEY = "___REDACTED___";
var TWITTER_CONSUMER_SECRET = "___REDACTED___";
var TWITTER_HANDLE = "___REDACTED___";
var SEARCH_QUERY = "___REDACTED___" + TWITTER_HANDLE;
// Store variables
ScriptProperties.setProperty("TWITTER_CONSUMER_KEY", TWITTER_CONSUMER_KEY);
ScriptProperties.setProperty("TWITTER_CONSUMER_SECRET", TWITTER_CONSUMER_SECRET);
ScriptProperties.setProperty("TWITTER_HANDLE", TWITTER_HANDLE);
ScriptProperties.setProperty("SEARCH_QUERY", SEARCH_QUERY);
ScriptProperties.setProperty("SINCE_TWITTER_ID", "404251049889759234");
// Delete exiting triggers, if any
var triggers = ScriptApp.getScriptTriggers();
for(var i=0; i < triggers.length; i++) {
ScriptApp.deleteTrigger(triggers[i]);
}
// Setup trigger to read Tweets every 2 hours
ScriptApp.newTrigger("fetchTweets")
.timeBased()
.everyMinutes(30)
//.everyHours(2)
.create();
}
function oAuth() {
//Authentication
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(ScriptProperties.getProperty("TWITTER_CONSUMER_KEY"));
oauthConfig.setConsumerSecret(ScriptProperties.getProperty("TWITTER_CONSUMER_SECRET"));
}
function fetchTweets() {
oAuth();
// I put this line in to monitor whether the property is getting "stored" so as to avoid
// reading in duplicate tweets.
Logger.log("Getting tweets since " + ScriptProperties.getProperty("SINCE_TWITTER_ID"))
var twitter_handle = ScriptProperties.getProperty("TWITTER_HANDLE");
var search_query = ScriptProperties.getProperty("SEARCH_QUERY")
Logger.log("searching tweets to " + search_query + '\n');
// form the base URL
// restrict to a certain radius ---:
//var search = "https://api.twitter.com/1.1/search/tweets.json?count=5&geocode=42.827934,-83.564306,75mi&include_entities=false&result_type=recent&q=";
// unrestricted radius:
var search = "https://api.twitter.com/1.1/search/tweets.json?count=5&include_entities=false&result_type=recent&q=";
search = search + encodeString(search_query) + "&since_id=" + ScriptProperties.getProperty("SINCE_TWITTER_ID");
var options =
{
"method": "get",
"oAuthServiceName":"twitter",
"oAuthUseToken":"always"
};
try {
var result = UrlFetchApp.fetch(search, options);
var lastID = ScriptProperties.getProperty("SINCE_TWITTER_ID");
if (result.getResponseCode() === 200) {
var data = Utilities.jsonParse(result.getContentText());
if (data) {
var tweets = data.statuses;
//Logger.log(data.statuses);
for (var i=tweets.length-1; i>=0; i--) {
// Make sure this is a NEW tweet
if (tweets[i].id > ScriptProperties.getProperty("SINCE_TWITTER_ID")) {
lastID = (tweets[i].id_str);
var answer = tweets[i].text.replace(new RegExp("\#" + twitter_handle, "ig"), "").replace(twitter_handle, "");
// I find this TRY block may be necessary since a failure to send one of the tweets
// may abort the rest of the loop.
try {
Logger.log("found >> " + tweets[i].text)
Logger.log("converted >> " + answer + '\n');
sendTweet(tweets[i].user.screen_name, tweets[i].id_str, answer.substring(0,140));
// Update the script property to avoid duplicates.
ScriptProperties.setProperty("SINCE_TWITTER_ID", lastID);
Logger.log("sent to #" + tweets[i].user.screen_name + '\n');
} catch (e) {
Logger.log(e.toString() + '\n');
}
}
}
}
}
} catch (e) {
Logger.log(e.toString() + '\n');
}
Logger.log("Last used tweet.id: " + lastID + + "\n")
}
function sendTweet(user, reply_id, tweet) {
var options =
{
"method": "POST",
"oAuthServiceName":"twitter",
"oAuthUseToken":"always"
};
var status = "https://api.twitter.com/1.1/statuses/update.json";
status = status + "?status=" + encodeString("RT #" + user + " " + tweet + " - Thanks\!");
status = status + "&in_reply_to_status_id=" + reply_id;
try {
var result = UrlFetchApp.fetch(status, options);
Logger.log("JSON result = " + result.getContentText() + '\n');
}
catch (e) {
Logger.log(e.toString() + '\n');
}
}
// Thank you +Martin Hawksey - you are awesome
function encodeString (q) {
// Update: 09/06/2013
// Google Apps Script is having issues storing oAuth tokens with the Twitter API 1.1 due to some encoding issues.
// Henc this workaround to remove all the problematic characters from the status message.
var str = q.replace(/\(/g,'{').replace(/\)/g,'}').replace(/\[/g,'{').replace(/\]/g,'}').replace(/\!/g, '|').replace(/\*/g, 'x').replace(/\'/g, '');
return encodeURIComponent(str);
// var str = encodeURIComponent(q);
// str = str.replace(/!/g,'%21');
// str = str.replace(/\*/g,'%2A');
// str = str.replace(/\(/g,'%28');
// str = str.replace(/\)/g,'%29');
// str = str.replace(/'/g,'%27');
// return str;
}
When you use ScriptProperties.setProperty("KEY", "VALUE");, internally Script Properties will overwrite a duplicate key (i.e., if an old Property has the same key, your new one will replace it). So in your case, since you are using the same identifier for the key (SINCE_TWITTER_ID), it will replace any previous Script Property that is that key.
Furthermore, you can view Script Properties via File -> Project properties -> Project properties (tab). Imo Google didn't name that very well. User properties as specific to Google users. Script properties as specific to the Script Project you are working under.
Also, it probably isn't a good idea to include \n in your value when you set the property. That will lead to all sorts of bugs down the road, because you'll have to compare with something like the following:
var valToCompare = "My value\n";
instead of:
var valToCompare = "My value";
because the value in SINCE_TWITTER_ID will actually be "some value\n" after you call your fetchTweet() function.
Of course, one seems more logical I think, unless you really need the line breaks (in which case you should be using them somewhere else, for this application).
Its ok like that thou I dont know why you are adding \n at fhe end. Might confuse other code. You can see script properties in the script's file menu+ properties

how to declare five variables and declare each variable on its own line

I need a little bit more of a understanding with this. In the example I have I know I am doing something wrong because I can not pull it up in a windows screen. This is only one of the five variables I have. Another question do I have to put the javascript.css or can it just be the <script> I am not understanding the different use with the js.css or just using <script> thanks.
var stock[0] ="Cisco";
var changenet[0] ="0.155 up 0.72%";
var lastsale[0] =$21.775;
document.write("<p><strong>stock[0]<strong>: " + stock[0] +"Cisco" +
changenet[0] +" Up"+ lastsale[0] +"to buy is at.<\/p>");
ok I am going to show you what I have been working on for hours and still can not get it to pull up on a web page...
<!DOCTYPE html PUBLIC"-//W3C//DTD Xhtml 1.0 Strict//EN"
"http://www.w3.org.TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Project 4-1</title>
</head>
<body>
<script type="text/javascript">
<!--HIDE FROM INCOMPATIBLE BROWERS
var stock[0] ="Cisco";
var changenet[0] ="0.155 up 0.72%";
var lastsale[0] =$21.775;
document.write("<p><strong>stock[0]<strong>: " + stock[0] +"Cisco" + changenet[0] +" Up"+ lastsale[0] +"to buy is at.</p>");
var stock[1] ="Microsoft";
var changenet[1] ="0.085 down 0.78%";
var lastsale[1] =$27.61;
document.write("<p><strong>stcok1<strong>: " + stock[1] +"Microsoft" + changenet[1] +" down"+ lastsale[1] +"to buy it at.</p>");
var stock[2] ="intel";
var changenet[1] ="0.085 down 0.78%";
var lastsale[2] =$21.40;
document.write("<p><strong>stock2<strong>: " + stock[2] +"Intel" + changenet[2] +" up"+ lastsale[2] +"to buy it at.</p>");
var stock[3] ="NVIDIA";
var changenet[2] ="0.0212 up 0.10%";
var lastsale[3] =$24.908;
document.write("<p><strong>stock3<strong>: " + stock[3] +"NVIDIA" + changenet[3] +" down"+ lastsale[3] +"to buy it at.</p>");
var stock[4] ="apple";
var changenet[4] ="4.1301 down 1.20%";
var lastsale[4] =$340.1898;
document.write("<p><strong>stock4<strong>: " + stock[4]+"apple" + changenet[4] +" down"+ lastsale[4] +"to buy it at.</p>");
var stock[5] ="EA";
var changenet[5] ="0.4 down 2.60%";
var lastsale[5] =$17.62;
document.write("<p><strong>stock5<strong>: " + stock[5] +"EA" + changenet[5] +" down"+ lastsale[5] +"to buy it at.</p>");
//STOP HIDING FROM INCOMPATIBLE BROWERS-->
</script>
</body>
</html>
You need to learn better syntax: Thau's JavaScript Tutorial (beware it's a little outdated)
you don't need the [0] if stock, changenet, and lastsale are not arrays. If they are arrays then you should put the var only when you define the array for the first time.
without using arrays:
var stock = "Cisco",
changenet = "0.155 up 0.72%",
lastsale = 21.775; //amount in dollars
document.write("Stock: " + stock + ", Changenet: " + changenet + ", Last Sale: " + lastsale);
with using arrays:
var stock = [],
changenet = [],
lastsale = [];
stock[0] = "Cisco";
changenet[0] = "0.155 up 0.72%";
lastsale[0] = 21.755;
document.write("Stock: " + stock[0] + ", Changenet: " + changenet[0] + ", Last Sale: " + lastsale[0]);
If you plan to do calculations I would recommend doing something else for the changenet variable, like making it 2 different variables, one with the decimal number, and one for the perentage.
var stock[0] is weird, and probably incorrect Javascript syntax.
To declare an array, use either: var myArray = new Array(); (older style) or var myArray = [];
Eg, try:
var stock = [], changenet = [], lastsale = [];
stock[0] ="Cisco";
changenet[0] ="0.155 up 0.72%";
lastsale[0] = "$21.775"; // note that the $ needs to be part of a string!
document.write("<p><strong>stock[0]<strong>: " + stock[0] +"Cisco" +
changenet[0] +" Up"+ lastsale[0] +"to buy is at.<\/p>");
Or, a shorter solution since you are not actually using variables as arrays in your example:
var stock = "Cisco",
changenet = "0.155 up 0.72%",
lastsale = "$21.775"; // note that the $ needs to be part of a string!
document.write("<p><strong>stock<strong>: " + stock + "Cisco" +
changenet +" Up"+ lastsale +"to buy is at.<\/p>");
Added I just looked again at your document.write statement and I notice that you included your ref to stock within a string literal. It won't work that way. So you probably mean:
document.write("<p><strong>" + stock + "<strong>: " + stock + "Cisco" +
changenet +" Up"+ lastsale +"to buy is at.<\/p>");
// Instead of
document.write("<p><strong>stock<strong>: " + stock + "Cisco" +
changenet +" Up"+ lastsale +"to buy is at.<\/p>");
Added in response to comment:
well i need to declare 5 variables and each has to be on its on line. Then i have to write a statement for each one.
You can declare variables and initialize them at the same time. Or you can first declare them and then later set them. When you declare them, you don't have to repeat the var statement since the var statement can be used with multiple variables at one time. Eg
var stocks = [], // declaring a new array
stock = "Cisco", // declaring a simple var (stock) and initializing it
changenet; // declaring a simple var without initializing it.
// all of the above are part of one var statement.
// or, the same as the above, but written as multiple statements:
var stocks = []; // declaring a new array
var stock = "Cisco"; // declaring a simple var (stock) and initializing it
var changenet; // declaring a simple var without initializing it.
// note that the statements end with the ;
changenet = "0.155 up 0.72%"; // assigning a value to an existing variable
As guys mentioned, you can declare your variables this way:
var stock = "EA",
changenet = "0.4 down 2.60%",
lastsale = $17.62;
but just be careful, if accidentally you will end one line with ';', then other variables will be declared as global:
var stock = "EA", // will be local
changenet = "0.4 down 2.60%"; // will be local
lastsale = $17.62; // will be global
one little technique comes to help, you can declare variables this way (and this is my preferable one):
var stock = "EA"
, changenet = "0.4 down 2.60%"
, lastsale = $17.62;
now you at least see your "commas", and if one line ends with ';' then you get JS error:
var stock = "EA"
, changenet = "0.4 down 2.60%";
, lastsale = $17.62; // Syntax Error
Other stuff, about arrays/not arrays and declaring was mentioned by other, so I just wanted to complement their answers

Categories