[Solved] Wrap string in brackets but also having random value in string: [closed]


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…

8

solved Wrap string in brackets but also having random value in string: [closed]