JavaScript如何移除字符串中最后一组括号及括号内的内容
需求说明
现有字符串需要移除最后一组括号及括号内的内容,例如对于字符串"Hello my name is (john) (doe) (bob)",需要移除末尾的(bob),得到结果"Hello my name is (john) (doe)"。
目前已有代码可以取出最后一组括号内的值:
const str = "Hello my name is (john) (doe) (bob)"; const result = str.split('(').pop().split(')')[0]; console.log(result); // 输出: bob
实现方法
方法1:正则替换(推荐)
用正则精准匹配最后一组括号,连带括号前多余的空格一起替换为空,代码最简洁:
const str = "Hello my name is (john) (doe) (bob)"; // 匹配末尾最后一组括号及前置空格 const res = str.replace(/\s*\([^)]*\)$/, ''); console.log(res); // 输出: Hello my name is (john) (doe)
正则各部分作用:
\s*:匹配括号前0到多个空白字符,避免替换后末尾残留多余空格\(、\):转义后匹配左右括号(括号是正则特殊字符,必须转义才能匹配字面量)[^)]*:匹配括号内所有非右括号的内容$:锚定字符串末尾,确保只匹配最靠后的、在字符串末尾的括号组
如果最后一组括号不在字符串末尾(比如格式为"xxx (a) (b) (c) yyy"),可以用负向预查匹配全局最后一组括号:
const str = "Hello my name is (john) (doe) (bob) nice to meet you"; const res = str.replace(/\s*\([^)]*\)(?!.*\()/, ''); console.log(res); // 输出: Hello my name is (john) (doe) nice to meet you
其中(?!.*\()表示当前匹配的左括号后面不存在其他左括号,也就是定位到最后出现的那组括号。
方法2:字符串截取(无正则场景)
如果不想使用正则,可以基于字符串原生的lastIndexOf找到最后一个左括号的位置,直接截取前面的内容即可:
const str = "Hello my name is (john) (doe) (bob)"; const lastLeftPos = str.lastIndexOf('('); // 截取到最后一个左括号前的位置,清除末尾多余空格 const res = str.slice(0, lastLeftPos).trimEnd(); console.log(res); // 输出: Hello my name is (john) (doe)
注意:这个方法仅适用于最后一组括号在字符串末尾的场景,如果括号后还有其他内容,会把括号后的内容一并截断。
内容的提问来源于stack exchange,提问作者Medusa
相关产品推荐
相关产品推荐

