0

How can I do this using regex, replacing every string with ! wrapped in function:

Examples:

  • 3! => fact(3)

  • 2.321! => fact(2.321)

  • (3.2+1)! => fact(3.2+1)

  • (sqrt(2)+2/2^2)! => fact(sqrt(2)+2/2^2)

2

5 Answers 5

1

Given your examples, you don't need a regex at all:

var s = "3!"; //for example

if (s[s.length-1] === "!")
    s = "fact(" + s.substr(0, s.length-1) + ")";

Not doubling the parentheses for the last case just requires another test:

var s = "(sqrt(2)+2/2^2)!"; //for example

if (s[s.length-1] === "!") {
    if(s.length > 1 && s[0] === "(" && s[s.length-2] === ")") 
        s = "fact" + s.substr(0, s.length-1);
    else
        s = "fact(" + s.substr(0, s.length-1) + ")";
}
Sign up to request clarification or add additional context in comments.

Comments

0

My own answer i just found out was:

Number.prototype.fact = function(n) {return fact(this,2)}
str = str.replace(/[\d|\d.\d]+/g, function(n) {return "(" + n + ")"}).replace(/\!/g, ".fact()")

But I'll see if the other answers might be much better, think they are

1 Comment

[\d|\d.\d] isn't doing what you probably think it is. It's a character class that matches one character at a time: a digit, a pipe (|), or a period (\.). This is probably what you're looking for: \d+(?:\.\d+)?
0

Here is as the op requested; using regexp:

"3*(2+1)!".replace(/([1-9\.\(\)\*\+\^\-]+)/igm,"fact($1)");

You might end up with double parentheses:

"(2+1)!".replace(/([1-9\.\(\)\*\+\^\-]+)/igm,"fact($1)");

Comments

0
"(sqrt(2)+2/2^2)!".replace(/(.*)!/g, "fact($1)");

Fiddle with it!

(.*)!

  • Match the regular expression below and capture its match into backreference number 1 (.*)

    • Match any single character that is not a line break character .
    • Between zero and unlimited times, as many times as possible, giving back as needed (greedy) *
  • Match the character “!” literally !

1 Comment

I assumed there might be other characters in the string that do not need to be put in fact(...)
0
var testArr =  [];
testArr.push("3!");
testArr.push("2.321!");
testArr.push("(3.2+1)!");
testArr.push("(sqrt(2)+2/2^2)!");

//Have some fun with the name. Why not?
function ohIsThatAFact(str) {
    if (str.slice(-1)==="!") {
         str = str.replace("!","");
         if(str[0]==="(" && str.slice(-1)===")") 
             str = "fact"+str;
         else 
             str = "fact("+str+")";
    }
    return str;
}

for (var i = 0; i < testArr.length; i++) {
    var testCase = ohIsThatAFact(testArr[i]);
    document.write(testCase + "<br />");
}

Fiddle example

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.