136

Would it be possible to change

Hello, this is Mike (example)

to

Hello, this is Mike

using JavaScript with Regex?

0

5 Answers 5

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

Result:

"Hello, this is Mike"
5
  • 19
    note that .replace() does not change the string itself, it only returns a new string. So you still have to set the variable to be equal to what you changed.
    – Ayub
    Commented Oct 30, 2013 at 18:50
  • 3
    Where the parentheses are in the middle of a string, the regex above will remove all the whitespace around them. This is probably not good. Commented Nov 13, 2017 at 11:42
  • 1
    How to do inverse of this? I want (example) only
    – carte
    Commented Jan 23, 2020 at 7:26
  • 1
    Doesn't work if you have something like: It's a bit messed (up (right)) but it happens :)
    – TigrouMeow
    Commented Mar 2, 2020 at 2:15
  • Not a robust solution, it works on console but not within script tag for some reason tried it already many times. The other answer work just fine. Commented Jun 26, 2021 at 10:04
37
var str = "Hello, this is Mike (example)";

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

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

2
  • what's the point of question mark? Commented Oct 3, 2022 at 16:04
  • .*? is a non-greedy version of .* (match everything). In short, it matches upto the next thing it can match, in this case the closing parentheses. Google "non-greedy regex" for more details.
    – svenema
    Commented Feb 2, 2023 at 18:53
20

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

Where

(space) matches the character (space) literally

\( matches the character ( literally

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

*? matches between zero and unlimited times

\) matches the character ) literally

g matches globally

Code Example:

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

1
  • 1
    what's the point of "[\s\S]" when you can just use a dot, meaning any character? Commented Oct 3, 2022 at 16:05
8

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

        var prevStr;
        do {
            prevStr = str;
            str = str.replace(/\([^\)\(]*\)/, "");
        } while (prevStr != str);
1
  • Didn't need that to get rid of the brackets but didn't want to get rid of whitespace before paranetheses like most solutions are and this maintains it so thanks Commented Sep 1, 2022 at 12:45
3

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

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

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

2

Not the answer you're looking for? Browse other questions tagged or ask your own question.