5

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

3 Answers 3

21
"string()".replace(/\(.*?\)/, "replacement")
1
  • 2
    FYI: This solution includes the parentheses in the replacement. Which is not exactly what the OP asked. Jan 5, 2017 at 17:56
11

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

1
  • 2
    FYI: This solution includes the parentheses in the replacement. Which is not exactly what the OP asked. Jan 5, 2017 at 17:56
2

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.

2
  • You don't need /i there, parentheses don't have upper and lower cases - this is only useful when matching literals.
    – Kobi
    Apr 19, 2010 at 13:30
  • For future reference: this solution replaces text BETWEEN the parentheses. Solutions below by Kobi and Koctehko replace the text between the parenthasees and also the parenthasees themselves. Jan 5, 2017 at 17:55