let str = 'asdwazsgdsadf' + 'qetgsadfdf';
let str2 = `asdqwedd qrqwee
fqfqw
qrwrq`;
let v1 = 100;
let v2 = 200;
let v3 = v1 * v2;
let str3 = `\${v1} * \${v2} = \${v3}`;
let t1 = 'hong'
console.log('v1 : ', `${v1}`); // out = v1 :
console.log('t1 : ', `${t1}`); // out = t1 :
console.log('str2 : ', str2);
console.log('str3 : ', str3); // out = str3 : 100 * 200 = 20000
this is my template literal test code.
other people can use ${v1} but my code is look like null.
what's matter of this code?
Without knowing more I'd say that you should check your environment to be sure that it can run template literals.
Check this list: CanIUse
with
`${v1} * ${v2} = ${v3}`
you should get the console log:
"100 * 200 = 20000"
but, whenever u add that backslash it takes away the speciality of the immediate special character followed by it , in your case, ($)
Related
I have a number which looks number this:
800.60000305176541
This number changes all the time.
So I'm doing this:
var mynumber = 800.60000305176541
var changenumber = mynumber.toFixed(3);
This is displaying 800.600 ... I need it to display the last 3 like:
800.541
How can I do this?
You can convert to string and do your manipulations.
Please note we are loosing the right most digit due to limits of javascript.
var num = 800.60000305176541;
var str = "" + num
var arr = str.split(".");
var result = arr[0]
if (arr[1]) {
result += "." + arr[1].slice(-3)
}
console.log(num)
console.log(result)
You could also try to solve it mathematically.
800.60000305176541
800.60000305176000 -
------------------
800.00000000000541
.00000000000541
10^10. X
------------------
0,541 + 800 = 800.541
I am trying to parse through math within strings. It works for x*y but not x*y*z. I think it has to do with one is a string while the other is a number. But I can't find a way to get around it.
Here is my code:
var reMD = /(\d+) *[\*|\/] *(\d+)/g
var str = '17 * 13 * 4';
var ex;
runWhile();
function runWhile() {
var ex = reMD.exec(str);
if (ex !== null) {
if (ex.index === reMD.lastIndex) {
reMD.lastIndex++;
}
if (ex[0].indexOf('*') !== -1) {
var rep = parseInt(ex[1]) * parseInt(ex[2])
} else {
var rep = parseInt(ex[1]) / parseInt(ex[2])
}
var rep = rep.toString()
str = str.replace(ex[0], rep)
if (reMD.exec(str) !== null) {
runWhile()
}
}
}
alert(str)
The alert sends back 221 * 4 but it should come back as 884. How would I fix this?
It should work if you remove the g flag from your regex, because then each time you call .exec() it will start afresh as explained at MDN. You can also remove the code that is messing with reMD.lastIndex.
(With the g flag, it tries to match from the index of where the previous match ended, but you are trying to match against a new string.)
Note also that you could change your regex to match the operator too, rather than using indexOf(), and you don't really need to call parseInt() because the * and / operators will coerce their operands to numbers:
var reMD = /(\d+) *([\*|\/]) *(\d+)/
var str = '17 * 13 / 4'; // note I've change the input to demostrate * and /
runWhile();
function runWhile() {
var ex = reMD.exec(str);
if (ex !== null) {
if (ex[2]==="*") {
var rep = ex[1] * ex[3]
} else {
var rep = ex[1] / ex[3]
}
rep = rep.toString()
str = str.replace(ex[0], rep)
if (reMD.exec(str) !== null) {
runWhile()
}
}
}
console.log(str)
(Note: it's still a little bit untidy for the function to be using and modifying variables defined outside the function, but I'll leave any further tidy-up as an exercise for the reader...)
I don't know if this will suffice for your project but it works
'17 * 13 * 4'.replace(/(\d+)( *[\*|\/] *(\d+))*/g, eval)
I am making a calculator in JavaScript and I want to know how to turn a string into an expression.
var numbers = "5+5+6";
numbers = +numbers;
document.querySelector('.screen').innerHTML = numbers;
Adding + before the variable does not seem to work. I would appreciate it if someone helped.
You can use the eval() function like this:
var numbers = "5+5+6";
document.querySelector('.screen').innerHTML = eval(numbers);;
Evaluate/Execute JavaScript code/expressions:
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
The result of res will be:
200
4
27
Without using eval, which is cheating - you could always write a simple calculator app.
First, take advantage of String.split() as follows
var numbers = "5+5+6";
numbers.split("");
// => ["5","+","5","+","6"]
Now all you need to do is figure out how to evaluate it while keeping the order of operations correct. Hint: it might involve trees.
Try using String.prototype.match() , Array.prototype.reduce() , Number() . See also Chrome App: Doing maths from a string
var numbers = "5+5+6";
var number = numbers.match(/\d+|\+\d+|\-\d+/g)
.reduce(function(a, b) {
return Number(a) + Number(b)
});
document.querySelector(".screen").innerHTML = number;
<div class="screen"></div>
How can I, using Javascript, make a function that will trim string passed as argument, to a specified length, also passed as argument. For example:
var string = "this is a string";
var length = 6;
var trimmedString = trimFunction(length, string);
// trimmedString should be:
// "this is"
Anyone got ideas? I've heard something about using substring, but didn't quite understand.
Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.
var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
Copying Will's comment into an answer, because I found it useful:
var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ?
string.substring(0, length - 3) + "..." :
string;
Thanks Will.
And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)
I suggest to use an extension for code neatness.
Note that extending an internal object prototype could potentially mess with libraries that depend on them.
String.prototype.trimEllip = function (length) {
return this.length > length ? this.substring(0, length) + "..." : this;
}
And use it like:
var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr
From link:
string.substr(start[, length])
let trimString = function (string, length) {
return string.length > length ?
string.substring(0, length) + '...' :
string;
};
Use Case,
let string = 'How to trim a string to N chars in Javascript';
trimString(string, 20);
//How to trim a string...
Prefer String.prototype.slice over the String.prototype.substring method (in substring, for some cases it gives a different result than what you expect).
Trim the string from LEFT to RIGHT:
const str = "123456789";
result = str.slice(0,5); // "12345", extracts first 5 characters
result = str.substring(0,5); // "12345"
startIndex > endIndex:
result = str.slice(5,0); // "", empty string
result = str.substring(5,0); // "12345" , swaps start & end indexes => str.substring(0,5)
Trim the string from RIGHT to LEFT: (-ve start index)
result = str.slice(-3); // "789", extracts last 3 characters
result = str.substring(-3); // "123456789" , -ve becomes 0 => str.substring(0)
result = str.substring(str.length - 3); // "789"
Little late... I had to respond. This is the simplest way.
// JavaScript
function fixedSize_JS(value, size) {
return value.padEnd(size).substring(0, size);
}
// JavaScript (Alt)
var fixedSize_JSAlt = function(value, size) {
return value.padEnd(size).substring(0, size);
}
// Prototype (preferred)
String.prototype.fixedSize = function(size) {
return this.padEnd(size).substring(0, size);
}
// Overloaded Prototype
function fixedSize(value, size) {
return value.fixedSize(size);
}
// usage
console.log('Old school JS -> "' + fixedSize_JS('test (30 characters)', 30) + '"');
console.log('Semi-Old school JS -> "' + fixedSize_JSAlt('test (10 characters)', 10) + '"');
console.log('Prototypes (Preferred) -> "' + 'test (25 characters)'.fixedSize(25) + '"');
console.log('Overloaded Prototype (Legacy support) -> "' + fixedSize('test (15 characters)', 15) + '"');
Step by step.
.padEnd - Guarentees the length of the string
"The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string. The source for this interactive example is stored in a GitHub repository."
source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
.substring - limits to the length you need
If you choose to add ellipses, append them to the output.
I gave 4 examples of common JavaScript usages. I highly recommend using the String prototype with Overloading for legacy support. It makes it much easier to implement and change later.
Just another suggestion, removing any trailing white-space
limitStrLength = (text, max_length) => {
if(text.length > max_length - 3){
return text.substring(0, max_length).trimEnd() + "..."
}
else{
return text
}
There are several ways to do achieve this
let description = "your test description your test description your test description";
let finalDesc = shortMe(description, length);
function finalDesc(str, length){
// return str.slice(0,length);
// return str.substr(0, length);
// return str.substring(0, length);
}
You can also modify this function to get in between strings as well.
Here is my solution, which includes trimming white space too.
const trimToN = (text, maxLength, dotCount) => {
let modText = text.trim();
if (modText.length > maxLength) {
modText = text.substring(0, maxLength - dotCount);
modText = modText.padEnd(maxLength, ".");
return modText;
}
return text;
};
trimToN('Javascript', 6, 2) will return "Java.."
I think that you should use this code :-)
// sample string
const param= "Hi you know anybody like pizaa";
// You can change limit parameter(up to you)
const checkTitle = (str, limit = 17) => {
var newTitle = [];
if (param.length >= limit) {
param.split(" ").reduce((acc, cur) => {
if (acc + cur.length <= limit) {
newTitle.push(cur);
}
return acc + cur.length;
}, 0);
return `${newTitle.join(" ")} ...`;
}
return param;
};
console.log(checkTitle(str));
// result : Hi you know anybody ...
Basically, I have a string of unknown numbers (determined by user input + my own math), and I need to split this string into 3 parts.
For example, I may have "1273498". I need to split it at the two characters, and the 3rd and 4th from the RIGHT, like so:
127
34
98
Another example: 1234567890 would need to be:
123456
78
90
Currently, I am accomplishing it this way:
// get first input box value
var depositgold = document.getElementById('v-gold').value;
// set it to 0 if it's empty
if(depositgold == null || depositgold == '')
depositgold = 0;
// second input box value
var depositsilver = document.getElementById('v-silver').value;
if(depositsilver == null || depositsilver == '')
depositsilver = 0;
// third input box value
var depositcopper = document.getElementById('v-copper').value;
if(depositcopper == null || depositcopper == '')
depositcopper = 0;
// combine the 3 input box values (adding dec to make split easier)
var depositnums = depositgold + '.' + depositsilver + depositcopper;
// do some math on our new value, then split it at out dec
var deposit12 = (0.15 * depositnums).toFixed(4).split(".");
// split the last part of the above split into 4 characters
var result12 = deposit12[1].split("", 3);
// keep the first part of out dec split
var deposit12gold = deposit12[0];
// combine the second part split results into paired numbers
var deposit12silver = result12[0] + result12[1];
var deposit12copper = result12[2] + result12[3];
// repeat the above process
var deposit24 = (0.30 * depositnums).toFixed(4).split(".");
var result24 = deposit24[1].split("", 3);
var deposit24gold = deposit24[0];
var deposit24silver = result24[0] + result24[1];
var deposit24copper = result24[2] + result24[3];
var deposit48 = (0.60 * depositnums).toFixed(4).split(".");
var result48 = deposit48[1].split("", 3);
var deposit48gold = deposit48[0];
var deposit48silver = result48[0] + result48[1];
var deposit48copper = result48[2] + result48[3];
I know there must be a much better (and more sane) way of accomplishing the above - I need to do it several more times for this project, and I'm certainly not looking forward to continuing to do it this way.
I am new to JS and programming, so laugh away, just try not to laugh too hard ;)
Try something along these lines:
var str = "123412341";
var matches = str.match(/(.+?)?(.{2})?(.{2})?$/);
// matches[1] = 12341
// matches[2] = 23
// matches[3] = 41
You may want to modify the RegEx depending on your input, currently all groups are optional.
Just use the substring method
var number = 123456789;
var one = number.substring( 0, number.length - 4 );
var two = number.substring( number.length -4, number.length - 2);
var three = number.substring( number.length - 2 );
Use the substr() method for this:
var L = mystring.length
var part1 = mystring.substr(0,L-4);
var part2 = mystring.substr(L-4,2);
var part3 = mystring.substr(L-2,2);
('1234'+'56'+'78').match(/(\d*)(\d\d)(\d\d)/)
["12345678", "1234", "56", "78"]
var number = 1234567890;
number = number.toString();
var a = number.substr(0, number.length - 4),
b = number.substr(-2),
c = number.substr(number.length - 4, 2);
console.log(a, b, c);
jsFiddle.
Output
123456 90 78
here is a function i made:
/**
* #param num A number to split like 382203849238
* #return Returns an array of size 3, where index 0 = 38220384, index 1 = 92, index 2 = 38 based on the example above
*/
function splitNumbers(num) {
var num = (typeof num == 'string' || typeof num == 'String') ? parseInt(num) : num,
rem = num % 10000;
return [Math.floor(num / 10000), Math.floor(rem / 100), rem % 100];
}
// Function to parse code in 3 parts
function parse_code_Split (code)
{
var len = code.length;
var divisor = (len / 3) >> 0; // get whole number
console.log(divisor);
var stringReg = "";
var regexp = ".{1," + divisor + "}";
try{
stringReg = new RegExp(regexp,"g");
}catch(Error){
window.console.log(Error.message);
}
codeSplit = code.match(stringReg);
// window.console.log(" codeSplit[0] " + codeSplit[0]);
// window.console.log(" codeSplit[1] " + codeSplit[1]);
// window.console.log(" codeSplit[2] " + codeSplit[2]);
// window.console.log(" codeSplit[3] " + codeSplit[3]); // remainder
return codeSplit;
}