Javascript regex in with special character in between -


hello can regex. string

((11a1:i19 + 11a1:k19 + 11a1:l19 + 11a1:i20 + 11a1:k20) - (11a1:n19 + 11a1:n20)) 

and regex

/([0-9a-z])\w+:\w+([0-9-a-z])/g 

i want take 11a1:i19, 11a1:k19, etc.. , replace values string (1767+154+1123 - (151-17)) full code

$f.each(function() {     var formula = $(this).data("formula");      var formula = $f.data("formula");      formula.split(/([0-9a-z])\w+:\w+([0-9-a-z])/g)         .foreach(function(el) {              if (el) {                  var hy = el.split(':');               let v = $('[data-sheet="' + hy[0] + '"][data-cell="' + hy[1] + '"]').val();              formula = formula.replace(el, v);              }         });       console.log(formula)      var result = eval(formula);      $f.val(result) }); 

i believe want (not tested jquery)

$f.each(function() { var formula = $(this).data("formula");  var formula = $f.data("formula");  formula.split(/([0-9a-z]+:[0-9a-z]+)/gi)     .foreach(function(el) {         if (el) {             var hy = el.split(':');             if (hy.length==2) {               let v = $('[data-sheet="' + hy[0] + '"][data-cell="' + hy[1] + '"]').val();               formula = formula.replace(el, v);             }          }     });   console.log(formula)  var result = eval(formula);  $f.val(result) }); 

update: after more thinking, code more compact , possibly easier read:

$f.each(function() { var formula = $(this).data("formula");  var formula = $f.data("formula");  var re=/([0-9a-z]+):([0-9a-z]+)/gi; var hy; var replaced=formula; while ((hy=re.exec(formula))!=null) {     let v = $('[data-sheet="' + hy[1] + '"][data-cell="' + hy[2] + '"]').val();     replaced = replaced.replace(hy[0], v); }  console.log(replaced) var result = eval(replaced); $f.val(result) }); 

for safety reasons, check v valid number before replacing in formula. avoid evaluating code might valid javascript expression dire consequences. can test with:

if (isnan(v+0)) continue; 

add before replacing hy[0] v.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -