Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Problem background -- I want to get the nth root of the number where user can enter expression like "the nth root of x'.I have written a function nthroot(x,n) which return proper expected output.My problem is to extract the value of x and n from expression.

I want to extract some matched pattern and store it to a an array for further processing so that in next step i will pop two elements from array and replace the result in repression.But I am unable to get all the values into an array without using loop.

A perl equivalent of my code will be like below.

$str = "the 2th root of 4+678+the 4th root of -10000x90";
@arr = $str =~ /the ([-+]?\d+)th\s?root\s?of\s?([-+]?\d+)/g;
print "@arr";

I want the javascript equivalent of the above code.

or

any one line expression like below.

expr = expr.replace(/the\s?([+-]\d+)th\s?root\s?of([+-]\d+)/g,nthroot(\\$2,\\$1));

Please help me for the same.

share|improve this question
can numbers be in hexadecimal form -10000x90?? – Anirudh 32 mins ago
and what is 4+678 in your input – Anirudh 31 mins ago
no 'x' can be used instead of '*'. x is for multiplication operation. – virus 30 mins ago
$str = "the 2th root of 4+678+the 4th root of -10000x90"; basically it is a mathematical expression.User is allowed to enter in above form.So I need to convert it to its mathematical equivalent "2+678+(7.07106781+7.07106781i)*90" where i is root of -1(Complex number). – virus 26 mins ago

2 Answers

The .replace() method that you are currently using is, as its name implies, used to do a string replacement, not to return the individual matches. It would make more sense to use the .match() method instead, but you can (mis)use .replace() if you use a callback function:

var result = expr.replace(/the\s?([+-]\d+)th\s?root\s?of([+-]\d+)/,function(m,m1,m2){
  return nthroot(+m2, +m1);
});

Note that the arguments in the callback will be strings, so I'm converting them to numbers with the unary plus operator when passing them to your nthroot() function.

share|improve this answer
var regex=/the ([-+]?\d+)th\s?root\s?of\s?([-+]?\d+)/g;
expr=expr.replace(regex, replaceCallback); 

var replaceCallback = function(match,p1,p2,offset, s) { 
 return nthroot(p2,p1);
 //p1 and p2 are similar to $1 $2
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.