jQuery replace text between parentheses [closed]
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this questionI have a requirement to replace the text between () in a string.
"string()".replace(/\(.*?\)/, "replacement")
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)"
.
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.
精彩评论