Why use String interpolation? [duplicate] - javascript

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

Related

Convert "10/2" to a number? [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 1 year ago.
I am working on a discord.js and have a found the following problem, I want to convert the users input into a number I am working on a calc bot so the arguments were like 10/2 but I couldn't find a method of converting the string into a number so I thought i would ask, I thought maybe the Number function could work but it didn't and tried using arrays but the join function simply converts it to a string. Anyone know how to solve this?
If you want to avoid the use of eval, you need to parse out the numbers, convert them to numbers, and perform the appropriate operation.
const rx = /(\d+(?:\.\d+)?)\s*([+\-\*\/%])\s*(\d+(?:\.\d+)?)/;
function math(str) {
const [full, lhs, op, rhs] = rx.exec(str);
let retval
switch (op) {
case '+':
retval = Number(lhs) + Number(rhs);
break;
// etc...
}
return retval;
}
console.log("1 + 1 = ", math("1 + 1"));
console.log("1.1 + 1.1 = ", math("1.1+1.1"));
Note that the code above doesn't have any error checking to bail if the string provided isn't a valid operation, or if the numbers aren't really numbers. It's only an example of how you can use a regular expression to get these values, and avoid using the potentially dangerous eval.
The easiest way to do this is by using eval() which takes a string containing javascript code, evaluates it, and returns the result.
WARNING: this is very dangerous and you can send any javascript code with it and javascript will happily execute it.
This would give users of the bot the ability to do any command and basically take remote control of your computer/server.
To protect yourself from this you should make sure that the string only contains some allowed characters like this:
const allowedChars = "1234567890/*+-% ";
const input = "2323 + 323";
if (![...input].some(x => !allowedChars.includes(x))) {
// safe to evaluate
const result = eval(input);
} else {
// not safe to execute
}

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"

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

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.

java script: 3 + 0 = 30 [duplicate]

This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 6 years ago.
JavaScript:
console.log('adding' + addThis + '+' + p1 +'=' + (addThis + p1));
Console in browser returns: adding3+0=30
Im debugging a loop that interpolates two numbers. It works fine until addThis (the amount that needs to be added to the original number) is exactly 3 and p1 (the original value) is 0.
Every time the difference(addThis) has no decimals a wrong calculation happens.
So same problem at:
adding6+0=60 ...or at..
adding9+0=90
...all cases in between work fine (e.g. console returns: adding3.5999999999999996+0=3.59999999999999960)
Dose it 'forget' the point?
Dose it treat those values as strings?
I can't share the whole code but the problem has to be in this simple calculation right?
Thanks a lot for your thoughts and knowledge! ;)
3+0=30. It seems like it must be the string (at least anyone variable is string). You can re-visit the lines where those variable values are initialized/changed. Else you can use like the below:
addThis=Number(addThis); p1=Number(p1);
console.log('adding' + addThis + '+' + p1 +'=' + (addThis + p1));
If you want to convert the strings to integers you can use the parseInt function:
addThis = '3'
p1 = '0'
console.log('adding' + addThis + '+' + p1 +'=' + (parseInt(addThis) + parseInt(p1)))

How to convert a whole array from strings to integers/numbers in javascript [duplicate]

This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 6 years ago.
I need to make it so that rather than 1+1=11 my code will return 1+1=2
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [];
for (var i = 0; i < 7; i++) {
arr.push(prompt('Enter GTIN Digit ' + (i+1)));
}
alert('Full GTIN: ' + (arr [0]*3)+(+ arr [2]*3)+(arr [4]*3)+(arr [6]*3) + (arr [1])+(arr [3])+ (arr [5]) );
</script>
</body>
</html>
Just one character you need to add: a + (unitary plus) before the prompt:
arr.push(+prompt('Enter GTIN Digit ' + (i+1)));
This will do the conversion.
Secondly, you need to avoid converting it back to string in your alert. Put the whole calculation between brackets or else the first string will make all the + act as string concatenation:
alert('Full GTIN: ' + (arr[0]*3+arr[2]*3+arr[4]*3+arr[6]*3+arr[1]+arr[3]+arr[5]));
Or, using a reduce:
alert('Full GTIN: ' + arr.reduce((s, d, i) => s+(i%2?d:d*3), 0));
Convert the array
The unitary + solution seems the best to me, but if -- like you put in the title -- you really want to first build the array of strings and then convert the values, then use this statement:
arr = arr.map(Number);
Remarks
It is not user-friendly to ask repeated input via prompt. The user cannot interrupt that sequence or go back. Better is to use the input element with the number type.
You would need to validate the input. As soon as you have a NaN instead of a number, or the input consists of multiple digits instead of one, the calculation cannot work correctly, and so there is no use to finish the whole input cycle.
Use parseInt()
parseInt(1)+parseInt(1)

Categories

Resources