How to change date value to Unicode with Javascript? - javascript

How can I convert a month and year value into Unicode using Javascript? For instance, "6, 2013" would become "\u1046, \u1042\u1040\u1041\u1043" (Myanmar text).
Patrick pointed me to Codepen where I got this:
<script type="text/javascript">
var d = new Date();
var mn = (d.getMonth()+1);
var dn = d.getDate();
var yn = d.getFullYear();
var toMyanmar = function (string) {
var unicodeString = '';
for (var i=0; i < string.length; i++) {
var char = string[i];
if (parseInt(char),16) {
char = String.fromCharCode(string.charCodeAt(i) + 4112)
}
unicodeString += char;
}
return unicodeString;
}
document.write("<br/>Myanmar Date: ");
document.write(toMyanmar(''+ mn) + ', ');
document.write(toMyanmar(''+ dn) + ', ');
document.write(toMyanmar(''+ yn));
document.write("<br/>Date; Latin/Arabic numerals: " + mn + ', ' + dn + ', ' + yn);
</script>
<body style="font-family:'Myanmar Text',Arial;"></body>
Zero (0; u1040, #4160) was ignored by this script until I moved the radix number to the same line as "parseInt". (mmrtext.ttf or similar Unicode font is needed to see characters displayed.)
So, this now works well for my purpose. And I think will be be the basis for future transcoding of character pages since Myanmar-related languages use many different sets.
Thanks a million until you are better paid.
R. Holland

Check out http://buildingonmud.blogspot.com/2009/06/convert-string-to-unicode-in-javascript.html
You will have to add some checking if you only want to encode numbers (run each element through parseInt most likely), since it would encode the command and the spaces as well.

Related

Replace char by coma and substrate 1 to the third value in JS

Supposing I have this:
var date = '2017-06-02';
How can I get:
var date = '2017,5,2';
So, I need to :
replace the - by ,
remove the leading zero if applied for the first and second parameter.
remove 1 for the second value
Thanks so much.
Non-ninjutsu solution:
var date = '2017-06-02';
var y = date.split("-")[0];
var m = date.split("-")[1];
var d = date.split("-")[2];
var final = y + "," + (parseInt(m)-1) + "," + parseInt(d);
console.log(final);
Try this
var date = '2017-06-02'
function convertDate(date){
var ddmmyy = date.split('-');
var withRemovedZero = ddmmyy.map(function(x){return parseInt(x)});
withRemovedZero[1] = withRemovedZero[1] -1;
return withRemovedZero.join(",");
}
console.log(convertDate(date))
var date = '2017-06-22';
var parts = date.split("-"); // split by '-' to get an array of parts
parts[0] = +parts[0]; // convert to number to remove any leading 0's
parts[1]--; // increment or decrement the part you need
parts[2] = +parts[2]; // convert to number to remove any leading 0's
var newDate = parts.join(","); // join the parts together using ','
console.log(newDate);
parts[1]-- is the same as parts[1] = parts[1] - 1 (parts[1] is the second part i.e. '06'). The parts ar strings, but whe using an operator that only applies on numbers such as -, then the part get converted to a number. If you use the + operator, however, this will cause a problem, as + wil be regarded as string concatination and not as numerical addition. A safter appraoch is to convert the string to a number first (either implicitly using unary + operator, or explicitly using parseInt or Number):
parts[1] = parseInt(parts[1]) - or + theNumberYouWant;
You can do a regular expression based string replacement. The following uses capturing groups to get the year, month and day, then uses a function to produce the replacement text.
var date = '2017-06-02';
var output = date.replace(/(\d+)-(\d+)-(\d+)/, function(_, y, m, d) {
return y + ',' + (m - 1) + ',' + +d;
});
console.log(output);
The result of the subtraction on the month is a number not a string, so it drops any leading zero automatically, then for the day I've used the unary plus operator to convert it to a number to drop its leading zero (if present), and both are concatenated into a string with the required commas.
Using split you can do that.
var date = '2017-06-02';
var date_array = date.split("-");
var first = date_array[1].charAt(0);
if(first=='0'){
first = date_array[1].substr(1);
}
else{
first = date_array[1];
}
var second = date_array[2].charAt(0);
if(second=='0'){
second = date_array[2].substr(1);
}
else{
second = date_array[2];
}
var output = date_array[0]+","+first+","+second;
document.write(output);
Output,
2017,6,2 // If date is 2017-06-02
2017,12,24 // If date is 2017-12-24

Regex: How to return matches that are not in the bracket

So I technically already solved this issue, but I was hoping for a better solution using some funky regex.
The issue is:
We got strings this:
2+{2+(2)},
10+(20+2)+2
The goal is to match the 'plus' signs that are not in any sort of bracket.
i.e. in the previous strings it should match
2 + {2+(2)} ,
10 + (20+2) + 2
at the moment what I am doing is matching all plus signs, and then checking to see if the sign has any bracket in front of it (using regex), if it does then get rid of it.
I was hoping for a neater regex solution, is that possible?
To reiterate, I need the location of the strings, at the moment I am using javascript to do this, so ideally a js solution is preferred, but the pattern is really what I am looking for.
You could perhaps just replace everything inside () or {} with spaces:
'10 + (20+2) + 2'.replace(/\([^)]*?\)|\{[^}]*?\}/g, m => ' '.repeat(m.length));
This would result in
10 + + 2
Meaning the position of the strings aren't changed.
Note: It won't work well with nested things of the same type, ex (1 + (1 + 1) + 1), but it works with (1 + { 1 + 1 } + 1).
Bigger solution, using the same logic, but that works with nested stuff
var input = '10 + { 1 + (20 + (1 + { 3 + 3 } + 1) + 2) + 2 }';
var result = [];
var opens = 0;
for (var i = 0; i < input.length; ++i) {
var ch = input[i];
if (/\(|\{/.test(ch)) {
opens++;
result[i] = ' ';
}
else if (/\)|\}/.test(ch)) {
opens--;
result[i] = ' ';
}
else {
if (!opens) result[i] = input[i];
else result[i] = ' ';
}
}
result = result.join('');
// "10 + "

JavaScript substr(), Get Characters in the Middle of the String

I have a string, var str = "Runner, The (1999)";
Using substr(), I need to see if ", The" is contained in str starting from 7 characters back, then if it is, remove those characters and put them in the start. Something like this:
if (str.substr(-7) === ', The') // If str has ', The' starting from 7 characters back...
{
str = 'The ' + str.substr(-7, 5); // Add 'The ' to the start of str and remove it from middle.
}
The resulting str should equal "The Runner (1999)"
Please, no regular expressions or other functions. I'm trying to learn how to use substr.
Here you go, using only substr as requested:
var str = "Runner, The (1999)";
if(str.substr(-12, 5) === ', The') {
str = 'The ' + str.substr(0, str.length - 12) + str.substr(-7);
}
alert(str);
Working JSFiddle
It should be noted that this is not the best way to achieve what you want (especially using hardcoded values like -7 – almost never as good as using things like lastIndexOf, regex, etc). But you wanted substr, so there it is.
var str = "Runner, The (1999)";
if(str.indexOf(", The") != -1) {
str = "The "+str.replace(", The","");
}
If you want to use just substr:
var a = "Runner, The (1999)"
var newStr;
if (str.substr(-7) === ', The')
newStr= 'The ' +a.substr(0,a.length-a.indexOf('The')-4) + a.substr(a.indexOf('The')+3)
Use a.substr(0,a.length-a.indexOf('The')-4) to obtain the words before "The" and a.substr(a.indexOf('The')+3) to obtain the words after it.
So, you say that the solution should be limited to only substr method.
There will be different solutions depending on what you mean by:
", The" is contained in str starting from 7 characters back
If you mean that it's found exactly in -7 position, then the code could look like this (I replaced -7 with -12, so that the code returned true):
function one() {
var a = "Runner, The (1999)";
var b = ", The";
var c = a.substr(-12, b.length);
if (c == b) {
a = "The " + a.substr(0, a.length - 12) +
a.substr(a.length - 12 + b.length);
}
}
If, however, substring ", The" can be found anywhere between position -7 and the end of the string, and you really need to use only substr, then check this out:
function two() {
var a = "Runner, The (1999)";
var b = ", The";
for (var i = a.length - 12; i < a.length - b.length; i++) {
if (a.substr(i, b.length) == b) {
a = "The " + a.substr(0, i) + a.substr(i + b.length);
break;
}
}
}

JavaScript: create a string or char from an UTF-8 value

Same question as this, but with UTF-8 instead of ASCII
In JavaScript, how can you get a string representation of a UTF-8 value?
e.g. how to turn "c385" into "Å" ?
or how to turn "E28093" into "—" (m dash) ?
or how to turn "E282AC" into "€" (euro sign) ?
My question is NOT a duplicate of Hex2Asc. You can see for yourself: hex2a("E282AC") will transform the string into "â¬" instead of transforming it into "€" (euro sign) !!
I think this will do what you want:
function convertHexToString(input) {
// split input into groups of two
var hex = input.match(/[\s\S]{2}/g) || [];
var output = '';
// build a hex-encoded representation of your string
for (var i = 0, j = hex.length; i < j; i++) {
output += '%' + ('0' + hex[i]).slice(-2);
}
// decode it using this trick
output = decodeURIComponent(output);
return output;
}
console.log("'" + convertHexToString('c385') + "'"); // => 'Å'
console.log("'" + convertHexToString('E28093') + "'"); // => '–'
console.log("'" + convertHexToString('E282AC') + "'"); // => '€'
DEMO
Credits:
Javascript elegant way to split string into segments n characters long
Convert integer array to string at javascript
https://stackoverflow.com/a/14028246/74757
var hex = "c5";
String.fromCharCode(parseInt(hex, 16));
you have to use c5, not c3 85 ref: http://rishida.net/tools/conversion/
Lear more about code point and code unit
http://en.wikipedia.org/wiki/Code_point
http://www.coderanch.com/t/416952/java/java/Unicode-code-unit-Unicode-code

Is Subtracting Zero some sort of JavaScript performance trick?

Looking in the jQuery core I found the following code convention:
nth: function(elem, i, match){
return match[3] - 0 === i;
},
And I was really curious about the snippet match[3] - 0
Hunting around for '-0' on google isn't too productive, and a search for 'minus zero' brings back a reference to a Bob Dylan song.
So, can anyone tell me. Is this some sort of performance trick, or is there a reason for doing this rather than a parseInt or parseFloat?
Probably just a short-hand way to force the left-hand side into integer. Not as clear as calling a function, of course.
This tutorial on type-conversion states:
Any mathematical operator except the
concatenation/addition operator will
force type-conversion. So conversion
of a string to a number might entail
performing a mathematical operation on
the string representation of the
number that would not affect the
resulting number, such as subtracting
zero or multiplying by one.
This also reveals that "subtracting" is a better search term than "minus". :)
Various ways to coerse JS strings to numbers, and their consequences:
(source: phrogz.net)
I personally use *1 as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt() when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.
Based on a few quick and dirty benchmark runs, "1234" - 0 was about 50% faster than parseInt("1234") and 10% faster than +"1234" in Firefox 3.6.
Update:
My "quick and dirty" benchmark was not very useful because it was just converting the string "1234" in a loop. I tried again using a random list of numbers, and the results are all over the map. The three methods are all within 400-500 ms on this computer except when they jump to 1300 ms! I think garbage collection is interfering. Here is some code to play with in Firebug, in case I did something stupid:
function randomList() {
var list = [];
for (var i = 0; i < 1000000; i++) {
list.push("" + Math.floor(Math.random()*4000000000));
}
return list;
}
function testParseInt(list) {
console.log("Sanity check: parseInt('" + list[0] + "') = " + parseInt(list[0]) );
var start = new Date();
for (var string in list)
var tmp = parseInt(string);
var time = new Date() - start;
console.log("parseInt(string): " + time);
}
function testMinusZero(list) {
console.log("Sanity check: '" + list[0] + "' - 0 = " + (list[0] - 0));
var start = new Date();
for (var string in list)
var tmp = string - 0;
var time = new Date() - start;
console.log("string - 0: " + time);
}
function testUnaryPlus(list) {
console.log("Sanity check: +'" + list[0] + "' = " + (+list[0]));
var start = new Date();
for (var string in list)
var tmp = +string;
var time = new Date() - start;
console.log("+string: " + time);
}
function testPlusZero(list) {
console.log("Sanity check: '" + list[0] + "' + 0 = " + (list[0] + 0) + " Oh no!");
var start = new Date();
for (var string in list)
var tmp = string + 0;
var time = new Date() - start;
console.log("string + 0: " + time);
}
var numbers = randomList();
testParseInt(numbers);
testMinusZero(numbers);
testUnaryPlus(numbers);
testPlusZero(numbers);
Just a info, According to this site
using unary + operator is faster one than any of the following (which include '- 0'):
var numValue = stringValue - 0;
/* or */
var numValue = stringValue * 1;
/* or */
var numValue = stringValue / 1;
unary + operator also type-converts
its operand to a number and because it
does not do any additional
mathematical operations it is the
fastest method for type-converting a
string into a number.
This contradicts James' benchmark, although he may be might be correct. I think jQuery wouldn't utilise this syntax if it were slow.
Your main reason to use this syntax is if you have generic code that may be any number (int or float) and you want to do a type-sensitive compare (===)
If it's not an old relic that got lost, then it just tries to change the type to Number.
It really looks like a "performant" parseInt to me.

Categories