-4

How can I wrap a string in parantheses that has another random value in it? Look at this for explaining better to understand:

var str = "ss(X)+ss(X)"

INTO:

"(ss(X))+(ss(X))"

NOTE: X can be any value like: "223" or "abc" "2+2+2"

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Freezy Ize
  • 1,201
  • 2
  • 10
  • 11
  • 2
    What are the rules for placing parentheses? Are the substrings always separated by a `+` sign? – Fabrício Matté Feb 23 '13 at 16:08
  • no, replaceing using regex – Freezy Ize Feb 23 '13 at 16:15
  • 2
    Freezy: start by forgetting about how to solve this (regexes or not) and start by better defining the problem first: what are the rules about what parts of the string are to be parenthesised? Once this is well defined (both when and when not to insert parentheses) the solution will follow. – Richard Feb 24 '13 at 10:14
  • The rules's to find any word with a paranthese infront of it with a depending value after that and then one more parantheses and wrap it into parantheses eg: "hello(2+2/32^2.2-sqrt(2)) + (lol(2))" into: "(hello(2+2/32^2.2-(sqrt(2)))) + (lol(2))" – Freezy Ize Feb 24 '13 at 16:10

3 Answers3

1

If the string is random data, then this would be impossible, since you don't know what you actually want wrapped. Step 1: find out the condition for "this should be wrapped" versus "this should not be wrapped". We can then do a simple replacement:

var shouldbewrapped = /([a-zA-Z\(\)])+/g;
var wrapped = string.replace(shouldbewrapped, function(found) {
  return "(" + found + ")";
});

This does a regexp replace, but instead of replacing a string with a string, it replaces a string with the output of a function run on that string.

(note that the 'g' is crucial, because it makes the replace apply to all matches in your string, instead of stopping after running one replacement)

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
0

I think your going to need to do some string interpolation. Then you can set up some Math.random or whatever you want to generate randomness with.

Community
  • 1
  • 1
pizza247
  • 3,869
  • 7
  • 33
  • 47
0

You can try this:

str = str.replace(/\w*\(\d*\)/g, function () {return '(' + arguments[0] + ')';});

A live demo at jsFiddle


EDIT

Since you've changed the conditions, the task can't be done by Regular Expressions. I've put an example, how you can do this, at jsFiddle. As a side effect, this snippet also detects possible odd brackets.

function addBrackets (string) {
    var str = '(' + string,
        n, temp = ['('], ops = 0, cls;
    str = str.replace(/ /g, '');
    arr = str.split('');
    for (n = 1; n < arr.length; n++) {
        temp.push(arr[n]);
        if (arr[n] === '(') {
            ops = 1;
            while (ops) {
                n++;
                temp.push(arr[n]);
                if (!arr[n]) {
                    alert('Odd opening bracket found.');
                    return null;
                }
                if (arr[n] === '(') {
                    ops += 1;
                }
                if (arr[n] === ')') {
                    ops -= 1;
                }
            }
            temp.push(')');
            n += 1;
            temp.push(arr[n]);
            temp.push('(');
        }
    }
    temp.length = temp.length - 2;
    str = temp.join('');
    ops = str.split('(');
    cls = str.split(')');
    if (ops.length === cls.length) {
        return str;
    } else {
        alert('Odd closing bracket found.');
        return null;
    }   
}

Just as a sidenote: If there's a random string within parentheses, like ss(a+b) or cc(c*3-2), it can't be matched by any regular pattern. If you try to use .* special characters to detect some text (with unknown length) within brackets, it fails, since this matches also ), and all the rest of the string too...

Teemu
  • 22,918
  • 7
  • 53
  • 106
  • But it doesn't suppor +,-,*,/ – Freezy Ize Feb 24 '13 at 07:34
  • @FreezyIze You've edited your question (15 hours after I've answered it). In the original question you said, that there will be only digits within the parenthesis ("`NOTE: X can be any value like: "223" or "56".`" A direct citate from your _original_ question.) :-(. In a comment to Mike you said "`It is numbers but also large numbers like 12 with 2 digits"`. Anyway, `Regular Expressions` are supposed to parse _regular_ patterns, not _random_. I'm afraid you'll need a different approach to this task. – Teemu Feb 24 '13 at 08:46
  • @FreezyIze I've edited my answer. Please check, if you can use it now. – Teemu Feb 24 '13 at 12:25
  • Very good!!!, I can use it it's perfect!!, but only one problem, it doesn't support this: ss(ss(2)^ss(2)) INTO (ss((ss(2))^(ss(2)))) – Freezy Ize Feb 24 '13 at 16:18
  • @FreezyIze Indeed it doesn't, it answers only to your question, not new demands. It's purposed to extract outer "functions" from the operators, but you can easily develope the code further, to check inner "functions" as well. Actually, if you're creating a calculator, it wouldn't be even necessary, since the code does this: `(ss(ss(2)^ss(2)))` which should be evaluateable as is. – Teemu Feb 24 '13 at 16:46
  • See this -> http://stackoverflow.com/q/15037805/2101744 – Freezy Ize Feb 24 '13 at 17:12
  • And this is my calculator: http://calcy.comze.com/ – Freezy Ize Feb 24 '13 at 17:12
  • Umh... Too much TI-89 : ). I'd suggest you to fix these kind of things when ever user clicks the button or hits the key. Just catch those events, and modify the input before it's added to you evaluate string. – Teemu Feb 24 '13 at 17:20