Convert html decoded string to human readable string in nashorn [duplicate] - javascript

This question already has answers here:
HTML Entity Decode [duplicate]
(17 answers)
Unescape HTML entities in JavaScript?
(33 answers)
Closed 2 years ago.
I have some strings like this(encoded as utf-8):
توسعه.
I want to convert them to:
توسعه
How can I do that in javascript?
The solution needs to be compatible with nashorn, since I am running the code in a virtual engine in java.
NOTE: None of these HTML Entity Decode, Unescape HTML entities in Javascript? are acceptable for my question, since they do not work in nashorn.
P.S: I have searched for possible solutions, and it was suggested by many to use decodeURIComponent(escape(window.atob(yourString))) (with slight differences), which apparently does not work, as I have tried them in vscode(javascript).

Unclear if nashorn supports DOM methods, but typically you can do
var x = 'توسعه'
var y = document.createElement("div")
y.innerHTML = x;
console.log(y.textContent)

The string I mentioned in the question can be broke down to smaller parts separated by ;. Each part, is a combination of &# and a hex number(e.gx62A) corresponding to a character(ت).
Following code will do the job, by parsing input str and finding corresponding characters. The result is concatenation of characters.
human_readable = function (str) {
hex_code = str.match(/([^&#]+[\w][^;])|(\s)/g)
s = ''
for (j = 0; j < hex_code.length; j++) {
if (hex_code[j] != ' ') {
int_code = parseInt("0" + hex_code[j])
char = String.fromCharCode(int_code)
} else {
char = ' '
}
s = s + char
}
return s
}
console.log(human_readable('توسعه'))
P.S: I have assumed that if str contains white spaces, it will be simply ' ', and not the corresponding unicode.

Related

How to split a string with arbitrary arguments? [duplicate]

This question already has answers here:
How can I split a string into segments of n characters?
(17 answers)
How do you use a variable in a regular expression?
(27 answers)
Closed 2 years ago.
I'm struggling with a very simple problem.
lines = "hogefoobarwai"
I want to cut this string into 4 characters.
Like this.
hoge, foob, arwa, i
How to split?
I try to use split() with regex.
let vars = lines.match(/.{4}/g);
This is good. But if something like {4} is variable, it won't work.
for example
length = 6
let vars = lines.match(/.{length}/g);
this shows literally /.{length}/.
If anyone can tell me what it is, please let me know.
You could take a minimum length of one (for getting smaller substrings) and the length and build a new regular expression.
const
lines = "hogefoobarwai",
length = 4,
parts = lines.match(new RegExp(`.{1,${length}}`, 'g'));
console.log(parts);
try using a dynamically generated Regex:
const newRegEx = new RegEx('{' + length + '}', g)

What is the easier way to convert single string word without spaces into Title case within less code? [duplicate]

This question already has answers here:
How to capitalize first letter and lowercase the rest of the string
(8 answers)
Closed 2 years ago.
I have single string and I want to convert this to title case.
JS is not providing built in function.
var difficulty = "easy"; // medium, hard
difficulty[0].toUpperCase();
document.write(difficulty) // It is printing in small.
If you don't want to repeat the code multiple times, you can add a method to the String prototype, that would allow you to easily reuse the functionality many times
String.prototype.titleCase = function () {
var sentence = this.toLowerCase().split(" ");
for(var i = 0; i< sentence.length; i++){
sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1);
}
return sentence.join(" ");
}
var difficulty = "easy";
document.write(difficulty.titleCase());
document.write("<br/>")
document.write("medium".titleCase());
document.write("<br/>")
document.write("hard".titleCase());
This will also work on words with spaces, so very easy // would give "Very Easy"

Is there a better way to achieve this? '000000'.slice(0, -'434'.length) + '434' = '000434' [duplicate]

This question already has answers here:
convert '1' to '0001' in JavaScript [duplicate]
(4 answers)
Pad a number with leading zeros in JavaScript [duplicate]
(9 answers)
Closed 3 years ago.
Yep, the title says pretty much everything. Basically I want a default X-digit number which is all zeros. Then, from this number, I want to replace the last characters with other numbers. For example, if I have '434', and the default is '000000', the result should be '000434'.
In Ruby, this is the equivalent of doing '%.6d' % 434 and it returns '000434'. If the number I want to save has more than 6 digits, I just use that number instead. I realized that as I'm working with strings I could use this solution:
let base = '000000'
let str = '434'
console.log(base.slice(0, -str.length) + str)
Buuut, even if it's a simple approach, I don't know if it's the best. What daya' think?
For compatibility with older JS environments, you can depend only on a simpler slice:
(base + str).slice(-6)
For modern ones, padStart is available:
str.padStart(6, '0') // or String(num)
JavaScript has string.padStart(length, padString)
let str = '434'
const updated = str.padStart(6, '0')
console.log(updated)

How to use isNAN and separator issues [duplicate]

This question already has answers here:
How to remove comma from number which comes dynamically in .tpl file
(7 answers)
How can I parse a string with a comma thousand separator to a number?
(17 answers)
Closed 5 years ago.
I need to find a way of either inputting separator eg, 12,000 without getting NaN message and if this can't be done then showing a message instead. I have looked through various sites and StackOverflow and can't work out how to do this (newbeeee issue). Current code as follows:
<script language="JavaScript" type="text/javascript">
function calcsavings()
{
var B1=document.forms[0].B1.value;
var B2n = Number("1516");
var B2=+B2n + +B1;
var B4 = Number("0.138");
var t;
for (i=0; i<document.forms[0].ITR.options.length; i++)
{
if (document.forms[0].ITR.options[i].selected)
t = document.forms[0].ITR.options[i].value;
}
var result=(B1/t-(B2/(1+B4)))*t
result=Math.round(result);
document.getElementById("childcaresavings").innerHTML=result;
}
</script>
I have stripped out the non-working code I tried before posting.
Is there anything wrong with adding a NaN check for result?
result=Math.round(result);
var htmlContent = Number.isNaN(result) ? "not a valid number" : result;
document.getElementById("childcaresavings").innerHTML=htmlContent ;
edit: If you're looking for a casual use of parsing. You can just use a global replace that will remove anything except numbers and periods.
if (document.forms[0].ITR.options[i].selected) {
var inputVal = document.forms[0].ITR.options[i].value;
var removedCommas = inputVal.replace(/[,]/g, "")
if (removedCommas[0] === "£") {
removedCommas = removedCommas.slice(1, removedCommas.length)
}
t = removedCommas
}
What this does: It takes your input and removes all commas and £ if it is the first character in the input. Assuming your user enters a sane entry, it will process the number as expected. If your use enters anything weird like / * & #, etc, NaN will be returned and your error will show.

Why use String interpolation? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When is it better to use String.Format vs string concatenation?
Hi, I am writing String Interpolation for an open source Javascript library. I just get to know the concept of String interpolation and am a bit confused? Why do we even go into so much trouble to make String Interpolation? What are its advantages?
Also it there any resources on String interpolation in Javascript that you can point me to? Share with me?
Thanks
String interpolation is also known as string formatting. Advantages are:
1. code clarity
"<li>" + "Hello " + name + ". You are visitor number" + visitor_num + "</li>";
is harder to read and edit than
Java/.Net way
String.Format("<li> Hello {0}. You are visitor number {1}. </li>", name, visitor_num);
python way
"<li> Hello %s. You are visitor number %s</li>" % (name, visitor_num)
JavaScript popular way
["<li>","Hello",name,". You are visitor number",visitor_num,"</li>"].join(' ')
2. speed/memory use
Creating multiple strings and then concatenating them uses more memory and is slower than creating a single string one time.
I once wrote a javascript string formatter-
// simple string builder- usage: stringFormat("Hello {0}","world");
// returns "Hello world"
function stringFormat() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}

Categories

Resources