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"
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"
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)
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.
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...