views:

177

answers:

3

Hi,

I have a requirement to replace the text between () in a string.

+5  A: 
"string()".replace(/\(.*?\)/, "replacement")
Андрей Костенко
+2  A: 

You can use a regex - this isn't jQuery, but a part of JavaScript:

var s = "hello (there)";
s = s.replace(/\(.*?\)/, 'world');

For more than a single pair:

s = s.replace(/\(.*?\)/g, 'world');

This will not work if the parentheses contain more parentheses, mind you; another option is to use /\(.*\)/ to capture from first to last - "a (b (c) d)" --> "a world", but the same for "a (b) c (d)".

Kobi
+1  A: 

Rather than using JQuery, use regular expressions: http://www.w3schools.com/jsref/jsref_replace.asp

It's the second example, where you can specify a regex to target the ( and ), and then replace the inner contents... something like /(.+)/i as a regular expression should work.

HTH.

Brian
You don't need `/i` there, parentheses don't have upper and lower cases - this is only useful when matching literals.
Kobi
Good point, thanks.
Brian