jQuery替换括号中的文本

3 javascript string replace

我需要在字符串中替换()之间的文本.

Анд*_*нко 19

"string()".replace(/\(.*?\)/, "replacement")
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:此解决方案包括替换中的括号.这不是OP所要求的. (2认同)

Kob*_*obi 11

你可以使用正则表达式 - 这不是jQuery,而是JavaScript的一部分:

var s = "hello (there)";
s = s.replace(/\(.*?\)/, 'world');
Run Code Online (Sandbox Code Playgroud)

对于超过一对:

s = s.replace(/\(.*?\)/g, 'world');
Run Code Online (Sandbox Code Playgroud)

请注意,如果括号中包含更多括号,则无效; 另一个选择是使用/\(.*\)/从头到尾捕获"a (b (c) d)"- > "a world",但是相同 "a (b) c (d)".

  • 仅供参考:此解决方案包括替换中的括号.这不是OP所要求的. (2认同)