JavaScript/regex:删除括号之间的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4292468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:47:12  来源:igfitidea点击:

JavaScript/regex: Remove text between parentheses

javascriptregex

提问by Hyman moore

Would it be possible to change

有没有可能改变

Hello, this is Mike (example)

to

Hello, this is Mike

using JavaScript with Regex?

在正则表达式中使用 JavaScript?

回答by thejh

"Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, "");

Result:

结果:

"Hello, this is Mike"

回答by Tatu Ulmanen

var str = "Hello, this is Mike (example)";

alert(str.replace(/\s*\(.*?\)\s*/g, ''));

That'll also replace excess whitespace before and after the parentheses.

这也将替换括号前后多余的空格。

回答by Mamun

Try / \([\s\S]*?\)/g

尝试 / \([\s\S]*?\)/g

Where

在哪里

(space) matches the character (space) literally

(空格) 字面上匹配字符(空格)

\(matches the character (literally

\((字面上匹配字符

[\S\s]matches any character (\Smatches any non-whitespace character and \smatches any whitespace character)

[\S\s]匹配任何字符(\S匹配任何非空白字符并 \s匹配任何空白字符)

*?matches between zero and unlimited times

*?零次和无限次之间的匹配

\)matches the character )literally

\))字面上匹配字符

gmatches globally

g全球匹配

Code Example:

代码示例:

var str = "Hello, this is Mike (example)";
str = str.replace(/ \([\s\S]*?\)/g, '');
console.log(str);
.as-console-wrapper {top: 0}

回答by Marc

If you need to remove text inside nested parentheses, too, then:

如果您还需要删除嵌套括号内的文本,则:

        var prevStr;
        do {
            prevStr = str;
            str = str.replace(/\([^\)\(]*\)/, "");
        } while (prevStr != str);

回答by Pascalius

I found this version most suitable for all cases. It doesn't remove all whitespaces.

我发现这个版本最适合所有情况。它不会删除所有空格。

For example "a (test) b" -> "a b"

例如“a(测试)b”->“a b”

"Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, " ").trim(); "Hello, this is (example) Mike ".replace(/ *\([^)]*\) */g, " ").trim();

"Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, " ").trim(); "Hello, this is (example) Mike ".replace(/ *\([^)]*\) */g, " ").trim();