HTML Entity to Unicode conversion [duplicate] - javascript

This question already has answers here:
Decode HTML entities in JavaScript? [duplicate]
(3 answers)
Closed 8 years ago.
Is there some way to convert HTML Entities into unicode characters in Javascript?
I tried
var unicodeHtmlEntity = function (t) {
numericValue = parseInt(t.slice(2, -1), 10);
numericValue = numericValue.toString(16);
return "\\u" + numericValue;
};
Where the function can be called like €, but returns the string \u20ac, not the unicode character for € . Any ideas?

This should work for the vast majority of cases:
function unicodeHtmlEntity (t) {
var numericValue = parseInt(t.slice(2, -1), 10);
return String.fromCharCode(numericValue);
}
If you actually need to support characters in the "astral" planes, you can use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint#Getting_it_to_work_with_higher_values in place of String.fromCharCode().
I presume you are aware that your code does not deal with hexadecimal entities, only decimal ones. To support those you could do something like:
function unicodeHtmlEntity (t) {
var hex = t.charAt(2) === 'x';
var base = hex ? 16 : 10;
var pos = hex ? 3 : 2;
var numericValue = parseInt(t.slice(pos, -1), base);
return String.fromCharCode(numericValue);
}

Related

Reverse Integer Without converting to a string Javascript? [duplicate]

This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 2 years ago.
So i am trying to reverse an integer and so far the code works but i am trying to find a solution to reverse the integer without converting into a string first? Any help would be appreciated. This is my code snippet so far to reverse the integer.
function reverseInt(num) {
const reversed = num.toString().split('').reverse().join('')
return parseInt(reversed) * Math.sign(num)
}
console.log(reverseInt(-500));
I am trying to do it using javascript.
Try this:
function reverseInt(number) {
var isNegative = number < 0 ? true : false;
if(isNegative)
number = number * -1;
var reverse = 0, lastDigit = 0;
while (number >= 1) {
reverse = Math.floor(reverse * 10 + (number % 10));
number = number / 10;
}
return isNegative == true ? reverse*-1 : reverse;
}
console.log(reverseInt(-500));
console.log(reverseInt(501));

Convert float to string with at least one decimal place (javascript)

Let me give you an example.
var a = 2.0;
var stringA = "" + a;
I will get: stringA = "2", but I want: stringA = "2.0".
I don't want to lose precision however, so if:
var b = 2.412;
var stringB = "" + b;
I want to get the standard: stringB = "2.412".
That's why toFixed() won't work here. Is there any other way to do it, than to explicitly check for whole numbers like this?:
if (a % 1 === 0)
return "" + a + ".0";
else
return "" + a;
There is a built-in function for this.
var a = 2;
var b = a.toFixed(1);
This rounds the number to one decimal place, and displays it with that one decimal place, even if it's zero.
If you want to append .0 to output from a Number to String conversion and keep precision for non-integers, just test for an integer and treat it specially.
function toNumberString(num) {
if (Number.isInteger(num)) {
return num + ".0"
} else {
return num.toString();
}
}
Input Output
3 "3.0"
3.4567 "3.4567"
For other people looking at this question, it just occurred to me, that to convert a float to a string with at least n decimal places, one could write:
function toAtLeastNDecimalPlaces(num, n) {
normal_conv = num.toString();
fixed_conv = num.toFixed(n);
return (fixed_conv.length > normal_conv.length ? fixed_conv : normal_conv);
}
Note that according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed, toFixed() will work for at most 20 decimal places. Therefore the function above will not work for n > 20.
Also, the function above does not have any special treatment for scientific notation (But neither do any other answers in this thread).
If a is your float do
var a = 2.0;
var b = (a % 1 == 0) ? a + ".0" : a.toString();
Edited: add reference and change to allow for .0
http://www.w3schools.com/jsref/jsref_tostring_number.asp
This solution tries to balance terseness and readability
const floatString = (n) => Number.isInteger(n) ? n.toFixed(1) : n.toString();

Padding zero to the left of number in Javascript [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 8 years ago.
I have a ten digit number that will always be constant. I want to pad it so, that it will always remove a zero for every extra number added to the number. Can someone please show me an example of how I can do this?
eg. 0000000001
0000000123
0000011299
You can use this function:
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
Output
pad("123", 10); // => "0000000123"
JSFIDDLE DEMO
Just try with:
function zeroPad(input, length) {
return (Array(length + 1).join('0') + input).slice(-length);
}
var output = zeroPad(123, 10);
Output:
"0000000123"
Another variant would be:
function pad(input, length) {
return Array(length - Math.floor(Math.log10(input))).join('0') + input;
}
var out = pad(23, 4); // is "0023"

Javascript converting hex values automatically [duplicate]

This question already has answers here:
How to get hex color value rather than RGB value?
(24 answers)
Closed 9 years ago.
Currently I am heaving problems using this really simple bit of code: field.style.backgroundColor="#ffffff"; Till now it has worked fine for me, but just recently I noticed that in webkit the hex values is always converted to rgb values like rgb(255, 255, 255). Usually that wouldn't be a problem, but I need the hex values later on in a php script creating an image. And converting them back just slows down the whole process. So my really basic question is how can I avoid getting those annoying rgb values.
You can split the value into it's parts, convert each number to hexidecimal, then return a formatted string, e.g.:
// convert rgb colour values to hex, e.g. rgb(255, 255, 255) to #ffffff;
function rgbToHex(rgb) {
var re = /^rgb\(.*\)$/;
var bits;
function z(n){return (n<10?'0':'') + n;}
if (re.test(rgb)) {
bits = rgb.match(/\d+/g);
return '#' + z((+bits[0]).toString(16)) +
z((+bits[1]).toString(16)) +
z((+bits[2]).toString(16));
}
return rgb;
}
alert(rgbToHex('rgb(255, 255, 255)')); // #ffffff
alert(rgbToHex('rgb(0, 0, 0)')); // #000000
alert(rgbToHex('rgb(100, 230, 90)')); // #64e65a
You might need an i flag on the test regular expression in case some browsers return "RGB(…)".
Edit
Based on Xotic750's post, the z function should be:
function z(n){return (n.length == 1?'0':'') + n;}
A less strict regular expression may suit too:
var re = /^rgb/i;
The other fails are a case of garbage in, garbage out. The regular expression can be modified to allow a space in "rgb (" if required. An updated version is:
function rgbToHex(rgb) {
var re = /^rgb/i;
var bits = rgb.match(/\d+/g);;
function z(n) {
return (n.length == 1? '0' : '') + n;
}
if (re.test(rgb) && bits.length == 3) {
return '#' + z((+bits[0]).toString(16))
+ z((+bits[1]).toString(16))
+ z((+bits[2]).toString(16));
}
return rgb;
}
The only choice left is if the test fails, should it return the original string or undefined?
It is actually fairly trivial to write your own converters, and it is a really fast calculation, by why reinvent the wheel when there is one with a pneumatic tyre already fitted? :) Have a look at colours javascript library.
Ok, so the library wasn't your thing, here is a function to do it for you.
var a = "rgb(10, 128, 255)";
var b = "rgb( 10, 128, 255)";
var c = "rgb(10, 128, 255 )";
var d = "rgb ( 10, 128, 255 )";
var e = "RGB ( 10, 128, 255 )";
var f = "rgb(10,128,255)";
var g = "rgb(10, 128,)";
var rgbToHex = (function () {
var rx = /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;
function pad(num) {
if (num.length === 1) {
num = "0" + num;
}
return num;
}
return function (rgb, uppercase) {
var rxArray = rgb.match(rx),
hex;
if (rxArray !== null) {
hex = pad(parseInt(rxArray[1], 10).toString(16)) + pad(parseInt(rxArray[2], 10).toString(16)) + pad(parseInt(rxArray[3], 10).toString(16));
if (uppercase === true) {
hex = hex.toUpperCase();
}
return hex;
}
return;
};
}());
console.log(rgbToHex(a));
console.log(rgbToHex(b, true));
console.log(rgbToHex(c));
console.log(rgbToHex(d));
console.log(rgbToHex(e));
console.log(rgbToHex(f));
console.log(rgbToHex(g));
On jsfiddle
And here are the jsperfs
Can't you just interpret the value as a hex value in php without even the need of converting it?
Actually i don't know what JavaScript hands you there exactly but if it is just single value interpret them in hex and cocatenate them.
There shouldn't be a loss of performance.
Greetings

JavaScript format number to day with always 3 digits [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I create a Zerofilled value using JavaScript?
I have to output a day number that must always have 3 digits. Instead of 3 it must write 003, instead of 12 it must write 012. If it is greater than 100 output it without formatting.
I wonder if there's a regex that I could use or some quick in-line script, or I must create a function that should do that and return the result. Thanks!
How about:
zeroFilled = ('000' + x).substr(-3)
For arbitrary width:
zeroFilled = (new Array(width).join('0') + x).substr(-width)
As per comments, this seems more accurate:
lpad = function(s, width, char) {
return (s.length >= width) ? s : (new Array(width).join(char) + s).slice(-width);
}
I found an elegant solution by Samuel Mullen on his blog. I simply optimized the zeroes creation.
function lpad(value, padding) {
var zeroes = new Array(padding+1).join("0");
return (zeroes + value).slice(-padding);
}
Usage: lpad(12, 3) results in "012"
You can do this...
("00" + day).slice(-3)
It'll prepend the zeros, and then .slice() will always give you the last 3 values of the string.
Here is a simple function that pads a number with zeroes to a certain width:
function zeroFill(number, width) {
width -= number.toString().length;
if(width > 0) {
return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number;
}
return number + ""; // always return a string
}
(from How can I pad a value with leading zeros?)
Since the original answer did not explain how the function works I'll do it here.
width initially contains the total length you want, so width - number_of_digits is the number of padding chars necessary.
new Array(len + 1).join(str) repeats str len times.
The regex is used to add an additional padding zero in case of a number containing a decimal point since the point was also included in the number_of_digits determined using number.toString().length
One possible solution:
​while ((val+"").length < 3​) {
val = "0" + val;
}
DEMO: http://jsfiddle.net/WfXVn/
I would write the following function:
var pad = function(n, length) {
var str = "" + n;
if(str.length < length) str = new Array(length - str.length).join("0") + str;
return str;
};

Categories

Resources