JavaScript/regex: Remove text between parentheses

JavascriptRegex

Javascript Problem Overview


Would it be possible to change

Hello, this is Mike (example)

to

Hello, this is Mike

using JavaScript with Regex?

Javascript Solutions


Solution 1 - Javascript

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

Result:

"Hello, this is Mike"

Solution 2 - Javascript

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

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

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

Solution 3 - Javascript

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}

Solution 4 - Javascript

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

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

Solution 5 - Javascript

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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjack mooreView Question on Stackoverflow
Solution 1 - JavascriptthejhView Answer on Stackoverflow
Solution 2 - JavascriptTatu UlmanenView Answer on Stackoverflow
Solution 3 - JavascriptMamunView Answer on Stackoverflow
Solution 4 - JavascriptMarcView Answer on Stackoverflow
Solution 5 - JavascriptPascaliusView Answer on Stackoverflow