parsing and string substring at the same time in jquery - javascript

I have this line in my html
<td colspan="6" align="right" id="timer"><span>Timer : 50 <span></td>
I am intending to rewrite it into Timer : 60, str.substring to extract only the number 60 (and removing the "Timer : "), then parsing the 60 into a var Countdown (in Jquery)
My Jquery at the moment is
$("#timer").html("Timer : 60")
var str = ("#timer");
var strNum = str.substring(8);
var Countdown = parseInt($("StrNum"));
As you can see I am doing this in seperate steps (but I am not sure if I am correct here too, I am new to these). My question is, am I doing this right, and if is there a way to combine the str.substring and parsing into a single step? Thanks

You should read the basics of jquery. For example this line
var str = ("#timer");
Does absolutely nothing, and so the rest of your script... it should look something like this
var str = $("#timer span").html();
var strNum = str.substr(str.length - 3, 2);
var countdown = parseInt(strNum);
that should work, but you really should read about jquery and javascript

Related

Javascript extract last numbers from Math.random

So I'm trying to do a script for Photoshop with javascript and I can't get the last 6 number from a Math.random.
I tried using the same code as in Strings with "randomID.substr(randomID.length - 6);" or "randomID.substr(-6);" but that didn't work.
var kodi = 'FJ0B';
var randomID = Math.floor(Math.random() * (999999999999 - 100000000000 + 1) + 100000000000);
var lastSix = randomID.toFixed(-6);
var kontrataLayer = (kodi.charAt(0) + lastSix);
Math.floor works fine, I need it with 12 digits for another function.
Thank you.
What about:
var randomIDString = randomID.toString();
var lastSix = Number(randomIDString.substr(randomIDString.length - 6));
For substr to work you need to convert the number to a string. Maybe that's why it didn't work for you earlier?

match() or split() messing up my code

I'm new to programming, I'm learning javascript. I don't understand what's wrong with my code but I'm unable to reach the result (i.e. show the total seconds in the text box). The program works fine until matching the pattern. But it's getting all messed up when I'm using the split() function. Please tell me where I'm going wrong. Thank You
<body>
<script>
function cal() {
var text = document.getElementById("pp").innerHTML;
var pattern = text.match(/[0-2][0-9]:[0-5][0-9]:[0-5][0-9]/);
var b = pattern.split(':');
var seconds = (+b[0]) * 3600 + (+b[1]) * 60 + (+b[2]);
document.getElementById("tot").value = seconds;
}
</script>
<div>
<p id="pp">The Time Right Now Is 12:34:56</p>
Total Seconds: <input type=t ext id="tot"><button onclick="cal()"> Click Here!</button>
</div>
</body>
You can check the console (F12 in Chrome) to see if any errors occur. You can also step through the code to see what's going on by adding a debugger; statement there somewhere.
If you move the JavaScript code to a separate file, you can also write tests (for example with Jasmine) to automate testing your code.
All that being said, the following error is displayed in the console:
Uncaught TypeError: pattern.split is not a function
The fix:
var b = pattern[0].split(':');
But once you've started with a Regex, you can continue that way. The following will group the hours, minutes and seconds
var result = "12:34:56".match(/([0-2][0-9]):([0-5][0-9]):([0-5][0-9])/)
var hours = result[1];
var minutes = result[2];
var seconds = result[3];
Better yet, for date parsing like what you are doing here, you could use a library that offers this sort of things out of the box. MomentJS is a very popular one. If this is the only thing you do, using a library is overkill but if you are doing alot of date parsing/formatting, then it will make things much easier for you.
# Install on command line with npm (you can also use bower, ...)
npm install moment
// import and use
import * as moment from "moment";
var parsed = moment("12:34:56", "HH:mm:ss");
String.prototype.split() is a String method, and String.prototype.match() returns an array.
The problem:
You can not applay .split on the returned value from `.match
Solution:
You need to use array index [0] to match the first element from returned array.
Your code after fixing
function cal() {
var text = document.getElementById("pp").innerHTML;
var pattern = text.match(/[0-2][0-9]:[0-5][0-9]:[0-5][0-9]/);
var b = pattern[0].split(':');
var seconds = (+b[0]) * 3600 + (+b[1]) * 60 + (+b[2]);
document.getElementById("tot").value = seconds;
}
<div>
<p id="pp">The Time Right Now Is 12:34:56</p>
Total Seconds: <input type=t ext id="tot">
<button onclick="cal()"> Click Here!</button>
</div>
Pattern return as list. use conditional statement
<body>
<script>
function cal() {
var text = document.getElementById("pp").innerHTML;
var pattern = text.match(/[0-2][0-9]:[0-5][0-9]:[0-5][0-9]/);
b = pattern[0].split(':');
console.log(b)
var seconds = (b[0]) * 3600 + (b[1]) * 60 + (b[2]);
document.getElementById("tot").value = seconds;
}
</script>
<div>
<p id="pp">The Time Right Now Is 12:34:56</p>
Total Seconds: <input type=t ext id="tot"><button onclick="cal()"> Click Here!</button>
</div>
</body>

Addition not working in Javascript

I'm really new to Javascript and trying to create a form where I'm running into some trouble...
When I use + it does not add up to the value, instead it just puts it back to back. Ex: 5+10 (510)
Here's my code if you want to take a look at it. I'd appreciate any help since I can't figure this out on my own.
var service = document.getElementById("service");
var serviceprice = service.options[service.selectedIndex].id;
var tech = document.getElementById("tech");
var techprice = tech.options[tech.selectedIndex].id;
var hours = document.getElementById("hours").value;
// The error happens here
var total = techprice * hours + serviceprice;
I also have an html part which the script gets the data from.
That happens whenever you have a string rather than a number. The + operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt takes an argument to specify the base. You almost always want base 10.
Try changing this line:
var total = techprice * hours + serviceprice;
to
var total = techprice * hours + parseFloat(serviceprice);
I suspect 'servicePrice' is a string, and it will then try to concatenate the first value (let's say: 100) with the second value (which is, not a number, but a string, let's say 'test'), the result being '100test'.
Try to convert the string to int first with parseInt or to float with parseFloat
This is not especially elegant, but I find it simple, easy, and useful:
var total = -(-techprice * hours - serviceprice);
or even:
var total = techprice * hours -(-serviceprice);
They both eliminate the ambiguous + operator.

Javascript RegEx Mysteries (for a poor C programmer)

This is clearly a RTFM issue, but after I did so repeatedly I just can't get the damn thing to work so there are times when asking for help makes sense:
var text = "KEY:01 VAL:1.10,KEY:02 VAL:2.20,KEY:03 VAL:3.30";
var pattern = '/KEY:(\S+) VAL:([^,]+)/g';
//var pattern = '/KEY:(\S+) VAL:(.?+)(?:(?=,KEY:)|$)/g';
//var pattern = '/KEY:(\S+) VAL:(.+)$/g';
//pattern.compile(pattern);
var kv = null;
var row = 0, col = 0;
while((kv = pattern.exec(text) != null))
{
row = kv[1].charAt(0) - '0';
col = kv[1].charAt(1) - '0';
e = document.getElementById('live').rows[row].cells;
e[col].innerHTML = kv[2].slice(0, kv[2].indexOf(","));
}
kv[1] is supposed to give "01"
kv[2] is supposed to give "1.10"
...and of course kv[] should list all the values of 'text'
to fill the table called 'live'.
But I can't get to have pattern.exec() succeed in doing that.
Where is the glitch?
First, the delimiters for the RegExp should be /s, there's no need to put them in ' delimiters. i.e. to get your exec to run properly you should have:
var pattern = /KEY:(\S+) VAL:([^,]+)/g;
Second, you're assigning a boolean to kv which you don't want. The while will obviously only evaluate to true if it's not null so that's redundant. Instead you just need:
while (kv = pattern.exec(text)) {
That should get your code to work as you desire.
the syntax for pattern objects doesn't include quoting, such as:
var pattern=/KEY:(\S+) VAL:([^,]+)/g;
http://www.w3schools.com/jsref/jsref_regexp_exec.asp
It should be
var pattern = /KEY:(\S+) VAL:([^,]+)/g;
http://www.regular-expressions.info/ is a good place to start with.

How do I parse content with regular expression using jQuery?

I am trying to use jQuery to break right ascension and declination data into their constituents (hours, minutes, and seconds) and (degrees, arc-minutes, and arc-seconds), respectively from a string and store them in variables as numbers. For example:
$dec = "-35:48:00" -> $dec_d = -35, $dec_m = 48, $dec_s = 00
Actually, the data resides in a cell (with a particular class ('ra')) in a table.
At present, I have gotten this far:
var $dec = $(this).find(".ra").html();
This gives me the declination as a string but I cannot figure out how to parse that string.
I figured out the regular expression (-|)+\d+ (this gives me -35 from -35:48:00) to get the first part. How do I use that in conjunction with my code above?
This should do it:
var dec = '-35:48:00';
var parts = dec.split(':');
parts[0] would then be -35, parts[1] would be 48, and parts[2] would be 00
You could run them all through parseInt(parts[x], 0) if you want integers out of the strings:
var dec_d = parseInt(parts[0], 10);
var dec_m = parseInt(parts[1], 10);
var dec_s = parseInt(parts[2], 10);
I should point out this really has nothing to do with jQuery and is a Javascript problem (past getting the values out of the HTML document, at least) - The practice of prefixing a variable with a $ is usually done to signify that the variable contains a jQuery collection. Since in this situation it contains HTML, it is a little misleading
Use String.match()
$dec = "-35:48:00";
matches = $dec.match(/-*[0-9]+/g);
for (i=0;i<matches.length;i++){
alert(matches[i]);
}

Categories

Resources