Simon Hume
Simon Hume

Reputation: 1012

Removing content in Parentheses at the end of a string with JavaScript

I wonder if anyone can suggest a way of stripping the parentheses (and their content inside) and the preceding space from a JavaScript string?

I'm using an iTunes XML feed and a lot of the movie titles have the year included, or "extended edition" etc.

I'd like to strip these out and just have a nice clean movie title.

Here are a couple of examples of what the string looks like now:

Midnight Special (2016)

Friday (1995)

And what I'd like it to look like after the trim.

Midnight Special

Friday

The length of the string could vary, otherwise I'd do a trim to a certain length. Many thanks in advance

Simon

Upvotes: 0

Views: 76

Answers (2)

le_m
le_m

Reputation: 20228

You can use String.replace() with regex /\s*\(.*\)\s*$/gm:

"aaa (bb)".replace(/\s*\(.*\)\s*$/gm, ""); // "aaa"

var str = "aaa (bb)\ncccc \nddd ()";

console.log(str.replace(/\s*\(.*\)\s*$/gm, "")); // "aaa\ncccc\nddd"

Explanation: See https://regex101.com/r/dC0aP7/2

Regular expression visualization

Pitfalls: Be aware that this regex replaces aa (b) and cc (d) with aa.

If you only want the last parenthesis removed, use /\s*\([^\(]*\)\s*$/gm - which will however fail for aa (b(c)) which is replaced with aa (b.

Balanced parenthesis matching is not possible with regex alone.

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115232

Use String#replace method

str.replace(/\s*\(.*?\)$/gm, '')

var res = `Midnight Special (2016)

Friday (1995)`.replace(/\s*\(.+?\)$/gm, '')

console.log(res)


Regex explanation here.

Regular expression visualization

Upvotes: 1

Related Questions