I want an eval() function which will calculate brackets as same as normal calculations but here is my code
var str = "2(3)+2(5)+7(2)+2"
var w = 0;
var output = str.split("").map(function(v, i) {
var x = ""
var m = v.indexOf("(")
if (m == 0) {
x += str[i - 1] * str[i + 1]
}
return x;
}).join("")
console.log(eval(output))
Which takes the string str as input but outputs 61014 and whenever I try evaluating the output string, it remains same.
Obligatory "eval() is evil"
In this case, you can probably parse the input. Something like...
var str = "2(3)+2(5)+7(2)+2";
var out = str.replace(/(\d+)\((\d+)\)/g,(_,a,b)=>+a*b);
console.log(out);
while( out.indexOf("+") > -1) {
out = out.replace(/(\d+)\+(\d+)/g,(_,a,b)=>+a+(+b));
}
console.log(out);
You can do it much simplier, just insert '*' in a right positions before brackets
var str = "2(3)+2(5)+7(2)+2"
var output = str.replace(/\d\(/g, v => v[0] + '*' + v[1])
console.log(eval(output))
Related
I would like to intertwine(?) two strings, for example:
string A = 'HELLO WORLD!'
string B = '66666666666666666666' //twenty 6's
output = 'H6E6L6L6O6 6W6O6R6L6D6!666666666'
or for instance:
string A = 'SOME REALLY REALLY LONG STRING'
string B = '66666666666666666666' //twenty 6's
output = 'S6O6M6E6 6R6E6A6L6L6Y6 6R6E6A6L6L6Y6 6L6ONG STRING'
Is there an inbuilt function for doing something like this, what is it called?
Perhaps map?
function joinIt(strs) {
var strA = strs[0].length <= strs[1].length?strs[0]:strs[1];
var strB = strs[1].length <= strs[0].length?strs[0]:strs[1];
return strB.split("").map(function(b, i) {
var a = strA.charAt(i);
return b + a;
}).join("")
}
console.log(
joinIt(['HELLO WORLD!', '66666666666666666666'])
)
console.log(
joinIt(['SOME REALLY REALLY LONG STRING','66666666666666666666'])
)
There are no native JS functions, but it is a one-line function.
var stringA = 'SOME REALLY REALLY LONG STRING';
var stringB = '66666666666666666666'; //twenty 6's //twenty 6's
var stringC = '';
for (var i = 0; i < (Math.max(stringA.length, stringB.length)); i++) {
stringC += (stringA[i] ? (stringB[i] ? stringA[i] + stringB[i] : stringA[i]) : (stringB[i] ? stringB[i] : ''));
}
console.log('stringC: ', stringC);
function interleave(str1, str2){
let outstr = "";
for(let i = 0; i < Math.max(str1.length, str2.length);i++){
if(i < str1.length){
outstr += str1[i];
}
if(i < str2.length){
outstr += str2[i];
}
}
return outstr;
}
console.log(interleave('aaaaa','bbbbbbbbbbbb'));
Using replace() you could pass the match to a callback function, then, using shift() you get the first element of the second string (turned into array) each time we have a match, at the end you add the remaining elements using + arr.join(""):
function addSomethig(str, str2){
var arr = str2.split("");
str = str.replace(/[A-Z ]/gi, (m)=>(arr.length>0)?m+arr.shift():m) + arr.join("");
return str;
}
console.log(addSomethig('SOME REALLY REALLY LONG STRING', '66666666666666666666'));
console.log(addSomethig('HELLO WORLD!', '66666666666666666666'));
console.log(addSomethig('SOME REALLY REALLY LONG STRING', 'anything, like: 789798798798798'))
There's no inbuilt function, but it's easy to do:
var a = 'some long string';
var b = '2292929292302720709970709710';
var str1 = a.length < b.length ? b:a;
var str2 = a.length < b.length ? a:b;
var result = [...str1].reduce((acc, char, index) => {
acc += char + (str2[index] || '');
return acc;
}, '');
console.log(result);
There is the built in String.raw template tag function which does almost exactly what you ask;
var strA = 'SOME REALLY REALLY LONG STRING',
strB = '66666666666666666666',
strZ = String.raw({raw : strA}, ...strB);
console.log(strZ);
So... coming to the almost part, if strA is shorter than strB the remaining characters of strB are skipped.
var strA = 'HELLO WORLD!',
strB = '66666666666666666666',
zipS = String.raw({raw: strA},...strB);
console.log(zipS);
In this case we can add a simple logic to fix our code.
var zipStr = (s,t,d) => ( d = s.length - t.length
, String.raw({raw: s},...t) + (d < 0 ? t.slice(d) : "")
),
strA = 'HELLO WORLD!',
strB = 'SOME REALLY REALLY LONG STRING',
strC = '66666666666666666666',
zipAC = zipStr(strA,strC),
zipBC = zipStr(strB,strC);
console.log(zipAC);
console.log(zipBC);
I am using MikeMcl's big.js for precise accounting which outputs a string when calling toFixed().
I'd like to pretty print decimal results in an internationally aware way much like how the Date Object can automatically print dates and times in a local format.
Is there a way to format string objects that contain decimals internationally?
var myNumber = 123456.78;
console.log(myNumber.toLocaleString());
This should do the job.
function localize(fixed) {
/*Determine decimal symbol and digit grouping symbol.*/
var decimalSymbol = '.';
var digitGroupingSymbol = ',';
var dummy = 1234.5;
testResult = dummy.toLocaleString();
/*Browsers using digit grouping symbol.*/
if (testResult.length === 7) {
decimalSymbol = testResult[5];
digitGroupingSymbol = testResult[1];
}
/*Browsers not using digit grouping symbol.*/
if (testResult.length === 6) {
decimalSymbol = testResult[4];
digitGroupingSymbol = (decimalSymbol === '.'? ',': '.');
}
/*Format the number.*/
var result = '';
var dsIndex = fixed.indexOf('.');
if (dsIndex < 0) {
throw new Error('Expected decimal separator \'.\' in "' + fixed + '".');
}
for (var i = 0; i < dsIndex; ++i) {
if (fixed[i] < '0' || fixed[i] > '9') {
throw new Error('Expected digit, got "' + fixed[i] + '".');
}
if (i > 0 && i%3 === dsIndex%3) result += digitGroupingSymbol ;
result += fixed[i];
}
result += decimalSymbol + fixed.substr(dsIndex + 1);
return result;
}
/*Demonstration*/
var n1 = '123.4567890';
console.assert(localize(n1));
var n2 = '1234.567890';
console.log(localize(n2));
var n3 = '123456789012345678.1234567890';
console.log(localize(n3));
var n4 = '1234567890123456789.1234567890';
console.log(localize(n4));
var n5 = '12345678901234567890.1234567890';
console.log(localize(n5));
Output:
123.4567890
1.234.567890
123.456.789.012.345.678.1234567890
1.234.567.890.123.456.789.1234567890
12.345.678.901.234.567.890.1234567890
In my code I have a variable myCash, which is printed into an h1 element using javaScript's innerHTML. I found a function online that puts a comma after every third character from the end of the number so that the number is easier to read. I've tried for a couple of hours now sending my variable myCash into the function and then print it on the screen. I CANNOT get it to work.
I've tried just alerting the new variable to the screen after page load or by pressing a button, but I get nothing and the alert doesn't even work. Here's the comma insert function:
function commaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
now when I want my variable to change I've tried it a few different ways including this:
var newMyCash = commaFormatted(myCash);
alert(newMyCash);
and this:
alert(commaFormatted(myCash);
Where of course myCash equal some large number;
This does absolutely nothing! What am I doing wrong here??
Also,
Try this as a drop in replacement and try alerting the response:
http://phpjs.org/functions/number_format:481
Do you see any errors in the console of your browser (usually f12)?
This is not my function, but I hope it helps you.
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Usage:
var newMyCash = addCommas( myCash ); alert( newMyCash );
Source: http://www.mredkj.com/javascript/nfbasic.html
You are most likely not passing in a number that contains a decimal, which the function expects.
Working Demo
This is my integer value
12232445
and i need to get like this.
12,232,445
Using prototype how to get this?
var number = 12232445,
value = number.toString(),
parts = new Array;
while (value.length) {
parts.unshift(value.substr(-3));
value = value.substr(0, value.length - 3);
}
number = parts.join(',');
alert(number); // 12,232,445
It might not be the cleanest solution, but it'll do:
function addCommas(n)
{
var str = String(n);
var result = '';
for(var i = 0; i < str.length; i++)
{
if((i - str.length) % 3 == 0)
result += ',';
result += str[i];
}
return result;
}
Here is the function I use, to format thousands separators and takes into account decimals if any:
function thousands(s) {
var rx = /(-?\d+)(\d{3})/,
intDec = (''+s)
.replace(new RegExp('\\' + $b.localisation.thousandSeparator,'g'), '')
.split('\\' + $b.user.localisation.decimalFormat),
intPart = intDec[0],
decPart = intDec[1] || '';
while (rx.test(intPart)) {
intPart = intPart.replace(rx,'$1'+$b.localisation.thousandSeparator+'$2');
}
return intPart + (decPart && $b.localisation.decimalFormat) + decPart;
}
thousands(1234.56) //--> 1,234.56
$b.localisation is a global variable used for the session.
$b.localisation.thousands can have the values , or . or a space.
And $b.localisation.decimalFormat can have the values , or . depending on the locale of the user
This code generates a comma separated string to provide a list of ids to the query string of another page, but there is an extra comma at the end of the string. How can I remove or avoid that extra comma?
<script type="text/javascript">
$(document).ready(function() {
$('td.title_listing :checkbox').change(function() {
$('#cbSelectAll').attr('checked', false);
});
});
function CotactSelected() {
var n = $("td.title_listing input:checked");
alert(n.length);
var s = "";
n.each(function() {
s += $(this).val() + ",";
});
window.location = "/D_ContactSeller.aspx?property=" + s;
alert(s);
}
</script>
Use Array.join
var s = "";
n.each(function() {
s += $(this).val() + ",";
});
becomes:
var a = [];
n.each(function() {
a.push($(this).val());
});
var s = a.join(', ');
s = s.substring(0, s.length - 1);
You can use the String.prototype.slice method with a negative endSlice argument:
n = n.slice(0, -1); // last char removed, "abc".slice(0, -1) == "ab"
Or you can use the $.map method to build your comma separated string:
var s = n.map(function(){
return $(this).val();
}).get().join();
alert(s);
Instead of removing it, you can simply skip adding it in the first place:
var s = '';
n.each(function() {
s += (s.length > 0 ? ',' : '') + $(this).val();
});
Using substring
var strNumber = "3623,3635,";
document.write(strNumber.substring(0, strNumber.length - 1));
Using slice
document.write("3623,3635,".slice(0, -1));
Using map
var strNumber = "3623,3635,";
var arrData = strNumber.split(',');
document.write($.map(arrData, function(value, i) {
return value != "" ? value : null;
}).join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Use Array.join
var strNumber = "3623,3635,";
var arrTemp = strNumber.split(',');
var arrData = [];
$.each(arrTemp, function(key, value) {
//document.writeln(value);
if (value != "")
arrData.push(value);
});
document.write(arrData.join(', '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Using 'normal' javascript:
var truncated = s.substring(0, s.length - 1);
A more primitive way is to change the each loop into a for loop
for(var x = 0; x < n.length; x++ ) {
if(x < n.length - 1)
s += $(n[x]).val() + ",";
else
s += $(n[x]).val();
}
Sam's answer is the best so far, but I think map would be a better choice than each in this case. You're transforming a list of elements into a list of their values, and that's exactly the sort of thing map is designed for.
var list = $("td.title_listing input:checked")
.map(function() { return $(this).val(); })
.get().join(', ');
Edit: Whoops, I missed that CMS beat me to the use of map, he just hid it under a slice suggestion that I skipped over.
you can use below extension method:
String.prototype.trimEnd = function (c) {
c = c ? c : ' ';
var i = this.length - 1;
for (; i >= 0 && this.charAt(i) == c; i--);
return this.substring(0, i + 1);
}
So that you can use it like :
var str="hello,";
str.trimEnd(',');
Output: hello.
for more extension methods, check below link:
Javascript helper methods
Here is a simple method:
var str = '1,2,3,4,5,6,';
strclean = str+'#';
strclean = $.trim(strclean.replace(/,#/g, ''));
strclean = $.trim(str.replace(/#/g, ''));
s = s.TrimEnd(",".ToCharArray());
Write a javascript function :
var removeLastChar = function(value, char){
var lastChar = value.slice(-1);
if(lastChar == char) {
value = value.slice(0, -1);
}
return value;
}
Use it like this:
var nums = '1,2,3,4,5,6,';
var result = removeLastChar(nums, ',');
console.log(result);
jsfiddle demo