2

i have a dynamic string expression var expression = "count+count1+12-(count3+count4)";

I want to append v[...] in each string like this output

Output:-

v[count]+v[count1]+12-(v[count3]+v[count4]);

i have tried this regex expression,

expression = expression.replace(/[a-z]+|[A-Z]+/g, "v["/$1/"]").replace(/[\(|\|\.)]/g, "");

is it possible to write regex expression regex string.

1 Answer 1

2

You may use

var expression = "count+count1+12-(count3+count4)";
var res = expression.replace(/\b[a-z]\w*/ig, "v[$&]");
console.log(res);

Details:

  • \b - a leading word boundary
  • [a-z] - an ASCII letter
  • \w* - 0+ word chars ([a-zA-Z0-9_]).

The replacement contains $&, a backreference to the whole match.

Another solution that splits with the math operators and only wraps with v[...] those substrings that are not a number or the operator:

var expression = "count+count1+12+234.56-(count3+count4)";
var res = expression.split(/([-+\/*])/).map(function(x) {
   return /^(\d*\.?\d+|[-*\/+])$/.test(x) ? x : "v["+x+"]"; 
}).join("");
console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.