Regex replace anything but numbers with increments letter using javascript - javascript

I have an equation/formula stored in database and I want it to be triggered based on key up input event in a webpage.
Example formula: [55-57]
This is a simple minus operation, where the number actually represents the id of a row in database
I have looked at this solution which replaces numbers found in a string to new value. But I need the new value to be replaced with incremented letters such as a, b and so on. Also the leading and ending brackets [] need to be removed so that I can perform an eval later using JavaScript.
Later the equation will be convert to a-b. Variable a and b represent other HTML elements that holds a value. So whenever I key in something into text field, changes will reflect on other part of webpage. It's like auto computation.
Thank you for those helping this. Hope this question will help somebody.

Try something like this. If you need more help, you seriously need to re-word your question or post a jsfiddle, or something.
var eqn = '55-57'; // brackets removed. Remove them with a regex of /\[|\]/g if you need to
var result = eval( eqn.replace( /\w+/g, function( res ){
return +document.getElementById( res[1] );
} );
Basically this replaces 55 and 57 with the numerical values of #55 and #57. It would also work for #b, etc.
It then eval's the result, basically doing whatever math is in your equation.

Related

js dynamic regular expr [duplicate]

This question already has answers here:
Template literal inside of the RegEx
(2 answers)
Closed 1 year ago.
hi I am coding an online shop ,
currently working on add to cart functionality,
like to store product ids and their quantity in a cookie like this id1:qt1,id2:qt2...
like to check if a product is already is in cart , looks like my regular expr doesn't work
const reg = new RegExp(`${product_id}:\d+`);
if (!reg.test(cart_cookie)){
const values = cart_cookie.split(',');
values.push(`${product_id}:1`);
setCookie('cart', values.join(','), 7);
}
else {
console.log('already in cart.')
}
Yep, your regex is off :)
It stumped me for a second, but its clear when you check what your "regex" string actually evaluates to: /product_id:d+/. This is because the string you're passing in sees the \d as a literal d. To fix this, just throw another \ in there so the original \ is whats being escaped. Before, you were matching things like "apple:ddddddd".
Once you do that, your code DOES seem to work, but maybe just not like you expect it to?
I've put your code into a function, since you would -- presumably -- be calling this every time you want to add an item to the cart, and added a console.log statement to show the end value of the "cookie."
// Just as a stand in for actual values
let cart_cookie = 'apples:2,oranges:3,bananas:1';
function addCartItem(product_id) {
const reg = new RegExp(`${product_id}:\\d+`);
console.log(reg)
if (!reg.test(cart_cookie)){
const values = cart_cookie.split(',');
values.push(`${product_id}:1`);
console.log('cart_cookie is now ', values.join(','));
setCookie('cart', values.join(','), 7);
}
else {
console.log('already in cart.')
}
}
addCartItem('apples');
// already in cart.
addCartItem('kiwis');
// cart_cookie is now apples:2,oranges:3,bananas:1,kiwis:1
Its fixed! 🥳 But...
I'm not quite sure what your product ids look like, but if they contain special characters (e.g. periods, question marks, etc.) it'll cause some issues with how your regex performs. I doubt you have things like question marks in it, but something like this illustrates my point:
let cart_cookie = '123.15:3,2.5.141:1';
/* ... */
addCartItem('1.3.15');
// already in cart.
I know, its a rather unlikely scenario -- and it might not even apply to you if you know your product ids won't contain anything tricky -- but if you're goal is to build an online shop, you'll probably want to cover all your bases.
Even fixing that, this still has a potential issue, as this will only let you add a quantity of 1 to an item thats not already in the cart, with no ability to increment it after that. Not sure if thats what you're going for.
This veers off of the main question you posed, but a potentially better solution might be using the browser's localstorage (or sessionstorage) to keep track of the cart. This would allow you to use more familiar data structures to store this info, rather than a string that you have to pray you're parsing correctly.
More info on that here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
you can use just array method instead you don't need for regex for that,
for example..
const values = cart_cookie.split(',');
values.foreach(value => {
if(value != product_id){
values.push(`${product_id}:1`);
setCookie('cart', values.join(','), 7);
}
});

HTML to Javascript to PHP parameters giving weird values

I'm currently using Codeigniter to do basic CRUD. I have the following code
JS
function approve(args){
if(confirm('Do you want to approve this document?')){
window.location = "http://52.45.5.57/index.php/FinalizeCase/approve/" + args;
}else{
return false;
}
HTML with some PHP to loop all the PKs to generate something like this
<input type="submit" name="submit" value="Approve" onclick="approve(0000000004)"/>
<input type="submit" name="submit" value="Approve" onclick="approve(0000000008)"/>
But the weird this is, sometimes when I click the links I get really weird values i.e. for 15 I got 13. I thought maybe I mixed the loops or something and tried changing a cell to 215~ and when I tested it I got 140 even though my max cell and DB is around 15 excluding the one I raised for testing.
Checked the link params before clicking and it checked out with the corresponding value in the cell.
Tried using the following but it stayed the same, 251 becomes 141 and 12 becomes 8.
use a button instead of an input tag
use unique names and values in the html tag
Do you actually need the leading zeroes?
You're experiencing one of the disadvantages of loosely-typed languages such as php or JavaScript: the interpretor decides what type is each variable, not you. It saves work most of the time because "it just works" but sometimes the data type chosen by the interpreter is not what you'd expect and you end up here.
You may think your args are either strings or integers with a lot of leading zeroes, but the interpreters are actually seeing Octal numbers (which, when converted to decimal, change)
Depending on what is the actual type you expect, you have many alternatives:
If you expect the argument to be treated as a string, you need to keep the leading zeroes but prevent any interpretation as octal like this
function approve(args)
{
var a = String(args); // force the type to string
if(confirm('Do you want to approve this document?'))
{
window.location = "http://52.45.5.57/index.php/FinalizeCase/approve/" + a;
}
else
{
return false;
}
Just to be safe, you may also want to take the value in your controller and cast it as a string too. Assuming the args is also called $args in your PHP part, you may do something like
public function approve( (string) $args = null)
{
// Do whatever you need to do
}
This would also be my recommended course of action if your args are a zero-padded integer in the database.
If you need to considers args are strings, you should trim the leading zeroes and cast as int using parseInt(); in JavaScript and/or $args = (int) $args; in php
Like #Funk Forty Niner said.
The solution is simple, just remove the leading zeroes.
$str = ltrim($str, '0');

converting a string to float doesn't work

I got a variable Javascrpit which has a number as a string in this case 0.84. I'm trying to convert it into a float but when I try to it appears a 0 as float instead the 0.84.
I'm using this:
var pot="0.84";
var asd = parseFloat(pot);
console.log(asd);
EDIT:
This is not exactly the example. I recover data from the HTML and it works for other numbers but not for this. It is difficult to explain my problem exactly. It is a lot of code and works for other numbers so don't know exactly.
Your input is not "0.84". If you test with that, you will get the correct answer. Your input has something else inside, like spaces, for example:
"0 .84"
This should be the solution:
parseFloat(pod.replace(/ /g, ""))
I have tried this example on my end and it completely worked. However, you can try to instead input the string value directly into the parse float() function and it should print our your expected value. If you still want to assign the parsefloat() to a variable, then try to either rewrite the code or re-open your IDE because the code should work.
var pot = "0.84"
console.log(parseFloat(pot))
or you can just write it in one line
console.log(parseFloat("0.84"))

toFixed() Simple use/explanation in text field

I've avoided asking this question here as I know many have in the past. I've spent some time during the last few days trying to find a solution/figure out how the toFixed() method works. I've read a lot of questions on this site and tutorials on others but I'm still not getting it.
I have several text fields with the class, ".entry". A dollar amount is supposed to go here. When people type the following (examples):
1.2
5
6.35
8.
I need them to change to:
1.20
5.00
6.35
8.00
In other words, add the trailing zeros. I know this is accomplished through the toFixed() method but I'm completely at a loss. I can't get it to work.
I have a script I found that totals all the text fields in a DIV elsewhere on the page and I notice that it uses the toFixed() method:
$("#total").html(sum.toFixed(2).replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'));
}
I tried using that same code here so the zeros could display in the text field:
$('.entry').keyup(function(){
var str = this.value.replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1');
if (str!=this.value) this.value = str;
});
It doesn't work.
I'm new to Jquery and Javascript so I realize I'm probably missing something obvious. Most of the tutorials I've read set the variable in the code and then use "document.write" to display the variable with the correct number of zeros:
Example:
document.write( 1.1.toFixed(2) + '<br>' );
But this isn't what I'm looking for. I need it to show up in the text field.
Thanks in advance!
A few things:
Use the change event instead of keyup. If you use keyup, the text wil change every time the user tries to type something, which is an annoying user experience.
Consider using an input of type number with a step of 0.1.
With those in mind, I'd do something like this:
$('.entry').change(function(){
// parse the typed value as a floating point number
var num = parseFloat(this.value);
// ensure there are two decimal places
this.value = num.toFixed(2);
});
Note that if the user types something with more than two decimal places, the value will be rounded.
Example: http://jsfiddle.net/jndt1e02/

Javascript "Replace" not working on string returned via jQuery

I'm trying to convert a currency string to a number. I'm using a replace function with a regexp that I've used successfully in a similar context before.
The currency string is captured here, in part of an "each" loop:
var unitGridPrice = jQuery(this).find(".clsPriceGridDtlPrice").html();
The result is that unitGridPrice is a currency string, something like "$2.75". I'm trying to convert it to a number here:
var priceToConvert = unitGridPrice;
var unitGridPriceNo = Number(priceToConvert.replace(/[^0-9\.]+/g, ''));
However with that last line in place, the script will not run.
If I use the value of priceToConvert it correctly displays the currency text string, so I believe the string feeding the replace function is correct.
if I change "var priceToConvert = unitGridPrice" to "var priceToConvert = "$2.75" the script properly returns 2.75. I can copy and past the value that unitGridPrice displays into the text string I'm testing with and it works, but with the variable there the script dies.
I've tried removing the regex, changing the replace to .replace('$', '') and again the script stops with the variable in place but works if I test with a fixed string.
I'm really stumped. Help??!! Thank you!!!
i had some problem while try to get number from string also, little time ago. the problem is the regex, so i changed the regex like code below.
var id = element.name.replace ( /[^\d.]/g, '' );
element.name above is like input_21,input_22, etc. and i wanna get only the number(21,22).
hope it can help you. :)

Categories