简体   繁体   中英

Regex replace anything but numbers with increments letter using 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 ab . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM