How do I parse content with regular expression using jQuery? - javascript

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]);
}

Related

Mask the last two digits of a date in JavaScript using regex

I’m trying to demonstrate how a date would look like if it was displayed with some characters masked. Specifically, something like this:
10 August 2018 => 10 August 20**
10 August 2018 => 10 August **** (and this too if possible)
I’ve spent some time looking for working examples on here but haven’t found one for this specific example. In my own experiments I only ever end up with one asterisk (10 August 19*) instead of one per character.
It all needs to happen within a textToMask.replace(regex, '*').
I know you’d never use this in production; it’s for a visual demo.
You can use padEnd method
function maskIt(str, pad = 1) {
const slicedStr = str.slice(0,pad*-1);
const masked = slicedStr.padEnd(str.length, '*');
console.log(masked);
}
maskIt("10 August 2018",2);
maskIt("10 August 2018",4);
Here's a dirt simple mask() function, that works with any string, and doesn't involve regex:
function mask(str, amt = 1) {
if (amt > str.length) {
return '*'.repeat(str.length);
} else {
return str.substr(0, str.length-amt) + '*'.repeat(amt);
}
}
console.log(mask('10 August 2018', 2));
console.log(mask('10 August 2018', 4));
console.log(mask('test', 5));
Here is a very simple function that uses a regular expression to find a given number of digits at the end of a given date and substitutes them with an equal number of asterisks.
Example:
const mask_date = (date, n) => date.replace(new RegExp(`[\\d]{${n}}$`), "*".repeat(n));
console.log(mask_date("10 August 2018", 2));
console.log(mask_date("10 August 2018", 4));
Please note that I would really like to refactor this somehow, I just don't have the time to do it right now. Check back at some point tomorrow I may have made an edit to this to make the code flow a bit better.
I am using the second version of the String.prototype.replace function that allows you to pass a function instead of a string as the second parameter. Check the link to learn more.
This is a very rough function -- I unfortunately did not have a lot of time to write this out.
// str - string to be altered, pattern - regex pattern to look through, replacement - what to replace the found pattern with, match_length - do we match the length of replacement to the length of what it is replacing?
function mask(str, pattern, replacement="*", match_length=true){
return str.replace(pattern, function(whole, group){
//init some values;
let padLength = 0, returned = '';
// if the group is not a number, then we have a regex that has a grouping. I would recommend limiting your regex patterns to ONE group, unless you edit this.
if(typeof group != 'number'){
padLength = group.length;
returned = whole.slice(0, whole.indexOf(group)) + (replacement.repeat(match_length ? padLength : 1));
}else{
padLength = whole.length;
returned = replacement.repeat(match_length ? padLength : 1);
}
return returned;
});
}
let randomBirthdayString = 'April 3 2002';
console.log(mask(randomBirthdayString, /\d{2}(\d{2})$/) );
console.log(mask(randomBirthdayString, /\d{2}(\d{2})$/, 'x') );
console.log(mask(randomBirthdayString, /\d{2}(\d{2})$/, 'x', false) );
You can use the code below.
textToMask.replace(/..$/, '**')

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.

joining two variables in javascript

var s= new Date().getHours(); // 20
var m= new Date().getMinutes(); // 38
document.write(s,m); // returns 2038
var time = s,m;
document.write(time); // returns only 20
var time = s+m;
document.write(time); // returns 58
How can I declare a time variable which returns 2038 using s and m variables ?
Cast one to a string.
var time = ''+s+m;
document.write(time);
You have to make sure js knows its a string first.
var time = "" + s + m;
The longer answer is that JavaScript applies some rules when it sees code like this.
In this case document.write(s,m) is just outputting each value:
var s= new Date().getHours(); // 20
var m= new Date().getMinutes(); // 38
document.write(s,m); // returns 2038
The following is declaring two variables (separated by a comma), one called time and one called m, and the value contained in variable s is being assigned to time. With JavaScript scoping rules, you can declare e.g. var m as often as you like in a function and it will always refer to the same variable m:
var time = s,m;
document.write(time); // returns only 20
JavaScript uses + for both addition and concatenation, and will try to coerce variables to match the type of the first variable in order to decide whether it is to perform addition or concatenation. In this case s is a number so it will try to perform addition on the two values:
var time = s+m;
document.write(time); // returns 58
The correct JavaScript idiom for this is to put an empty string at the beginning of the expression and JavaScript will attempt to coerce subsequent variables to that type:
var time = '' + s + m;
document.write(time); // returns 2038

How do I get the unicode/hex representation of a symbol out of the HTML using JavaScript/jQuery?

Say I have an element like this...
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mo class="symbol">α</mo>
</math>
Is there a way to get the unicode/hex value of alpha α, &#x03B1, using JavaScript/jQuery? Something like...
$('.symbol').text().unicode(); // I know unicode() doesn't exist
$('.symbol').text().hex(); // I know hex() doesn't exist
I need &#x03B1 instead of α and it seems like anytime I insert &#x03B1 into the DOM and try to retrieve it right away, it gets rendered and I can't get &#x03B1 back; I just get α.
Using mostly plain JavaScript, you should be able to do:
function entityForSymbolInContainer(selector) {
var code = $(selector).text().charCodeAt(0);
var codeHex = code.toString(16).toUpperCase();
while (codeHex.length < 4) {
codeHex = "0" + codeHex;
}
return "&#x" + codeHex + ";";
}
Here's an example: http://jsfiddle.net/btWur/
charCodeAt will get you the decimal value of the string:
"α".charCodeAt(0); //returns 945
0x03b1 === 945; //returns true
toString will then get the hex string
(945).toString(16); // returns "3b1"
(Confirmed to work in IE9 and Chrome)
If you would try to convert Unicode character out of BMP (basic multilingual plane) in ways above - you are up for a nasty surprise. Characters out of BMP are encoded as multiple UTF16 values for example:
"🔒".length = 2 (one part for shackle one part for lock base :) )
so "🔒".charCodeAt(0) will give you 55357 which is only 'half' of number while "🔒".charCodeAt(1) will give you 56594 which is the other half.
To get char codes for those values you might wanna use use following string extension function
String.prototype.charCodeUTF32 = function(){
return ((((this.charCodeAt(0)-0xD800)*0x400) + (this.charCodeAt(1)-0xDC00) + 0x10000));
};
you can also use it like this
"&#x"+("🔒".charCodeUTF32()).toString(16)+";"
to get html hex codes.
Hope this saves you some time.
for example in case you need to convert this hex code to unicode
e68891e4bda0e4bb96
pick two character time by time ,
if the dec ascii code is over 127 , add a % before
return url decode string
function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2){
var dec = parseInt(hex.substr(i, 2), 16);
character = String.fromCharCode(dec);
if (dec > 127)
character = "%"+hex.substr(i,2);
str += character;
}
return decodeURI(str);
}

javascript dynamic regex vs hard typed and captures

I've been at this for hours -- I think I need sleep... but no matter how I alter the expression javascript will only capture the 1st and 3rd elements:
var number = 09416;
var mat = "([0-9]+/[0-9]+/[0-9]+\\s+[0-9]+:[0-9]+)\\s+([A-Z]+)\\s+[0-9,]+\\s+(.*?"+number+".+)";
// month / day / year hour : min AMPM byte size filename containing number in middle
var pattern = new RegExp(mat,"gi");
var arr = ['09/07/2010 07:08 PM 1,465,536 BOL09416 BOL31.exe',
'09/06/2010 12:13 PM 110,225 BOL09416_BOL030.exe',
'09/08/2010 04:46 AM 60,564 BOL09416_BOL32.exe',
'09/08/2010 01:08 PM 63,004 bol09416_bol33.exe']
for (var i=0;i<arr.length;i++){
var match = pattern.exec(arr[i]);
alert(match);
}
It is all spaces (no tabs), I've rewriten the regex to be as explainatory as possible... It correctly matches on arr[0] and arr[2], but nulls on the other two.
Tried looking for possible typo's, trying different .+,.*,.+? etc. All online matchers show that it should be working: Example
Anybody have any ideas as to what I'm missing?
====================
Update:
Going through all the awesome suggestions I am stumped even further:
var match = arr[i].match(/([0-9]+\/[0-9]+\/[0-9]+\s+[0-9]+:[0-9]+)\s+([A-Z]+)\s+[0-9,]+\s+(.*?09416.+)/g);
gives match[0] = full string match[1] = undefined. Basically no captures.
where as:
var match = /([0-9]+\/[0-9]+\/[0-9]+\s+[0-9]+:[0-9]+)\s+([A-Z]+)\s+[0-9,]+\s+(.*?09416.+)/g.exec(arr[i]);
DOES return match[0] = full string, match[1] = date, and so on.
So I guess my real question is how to include dynamically made RegExpressions, and have multiple captures? As the only difference between:
var number = "09416";
var mat = "([0-9]+/[0-9]+/[0-9]+\\s+[0-9]+:[0-9]+)\\s+([A-Z]+)\\s+[0-9,]+\\s+(.*?09416.+)";
var pattern = new RegExp(mat,'g');
and
/([0-9]+\/[0-9]+\/[0-9]+\s+[0-9]+:[0-9]+)\s+([A-Z]+)\s+[0-9,]+\s+(.*?09416.+)/g.exec(arr[i]);
is that I hard-typed the number.
var number = 09416;
// month / day / year hour : min AMPM byte size filename containing number in middle
var mat = '^(\d{2}\/\d{2}\/\d{4})\s+(\d{2}:\d{2}\s*[AP]M)\s+((\d+[\d,]?))\s+(.' + number + '.*)$';
var pattern = new RegExp(mat);
var arr = ['09/07/2010 07:08 PM 1,465,536 BOL09416 BOL31.exe',
'09/06/2010 12:13 PM 110,225 BOL09416_BOL030.exe',
'09/08/2010 04:46 AM 60,564 BOL09416_BOL32.exe',
'09/08/2010 01:08 PM 63,004 bol09416_bol33.exe']
for (var i=0;i<arr.length;i++){
var match = arr[i].match(pattern);
console.log(match);
}
Use string.match instead of regex.exec.
Edited
I've removed the global and it worked like it should be. I've also rewritten the regex but it's quite close to yours (not a big deal).
Look at the output by firebug below:
["09/08/2010 04:46 AM ...,564 BOL09416_BOL32.exe", "09/08/2010", "04:46 AM", "60,564", "564", "BOL09416_BOL32.exe"]
0 "09/08/2010 04:46 AM ...,564 BOL09416_BOL32.exe" //whole match
1 "09/08/2010" //date
2 "04:46 AM" //time
3 "60,564" //bytes
4 "564" // last digit of bytes (i can't take this off. but it's harmless)
5 "BOL09416_BOL32.exe" //name of file
I would suggest you try Regexr to build the expression.
try this
([0-9]+/[0-9]+/[0-9]+ +?[0-9]+:[0-9]+) +?([A-Z]+) +?[0-9,]+ +?(.*?09416.*)
Try this regex:
new RegExp('([0-9]+/[0-9]+/[0-9]+\\s+[0-9]+:[0-9]+)\\s+(AM|PM)\\s+([0-9,]+)\\s+([^0-9]*'+number+'.+)','gi')
Time
AM/PM
File size
File name

Categories

Resources