简体   繁体   English

使用JavaScript删除字符串末尾括号中的内容

[英]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? 我想知道是否有人可以建议从JavaScript字符串中去除括号(及其内部的内容)和前面的空格的方法?

I'm using an iTunes XML feed and a lot of the movie titles have the year included, or "extended edition" etc. 我正在使用iTunes XML feed,很多电影的标题都包含年份,或“扩展版”等。

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) 午夜特别(2016)

Friday (1995) 星期五(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 西蒙

Use String#replace method 使用String#replace方法

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

 var res = `Midnight Special (2016) Friday (1995)`.replace(/\\s*\\(.+?\\)$/gm, '') console.log(res) 


Regex explanation here. 正则表达式的解释在这里。

正则表达式可视化

You can use String.replace() with regex /\\s*\\(.*\\)\\s*$/gm : 您可以将String.replace()与正则表达式/\\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 说明:参见https://regex101.com/r/dC0aP7/2

正则表达式可视化

Pitfalls: Be aware that this regex replaces aa (b) and cc (d) with aa . 陷阱:请注意,此正则表达式将aa (b) and cc (d)替换为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 . 如果只希望删除最后一个括号,请使用/\\s*\\([^\\(]*\\)\\s*$/gm但是,对于aa (b(c))会失败,而将其替换为aa (b

Balanced parenthesis matching is not possible with regex alone. 单独的正则表达式不可能实现平衡的括号匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM