首页 > 解决方案 > 删除括号之间的文本,但仅在给定条件下

问题描述

我有以下句子:

敏捷的棕色狐狸跳过懒惰的狗(见第 1 册)。敏捷的棕色狐狸跳过懒狗(见上文)。敏捷的棕色狐狸跳过懒惰的狗(见第 2 册)。敏捷的棕色狐狸跳过懒惰的狗(见第 3 册)

我需要在以下条件下删除句子内的括号之间的文本 - 包括括号和外部空格:

所以那句话应该变成:

敏捷的棕色狐狸跳过了懒狗。敏捷的棕色狐狸跳过懒狗(见上文)。敏捷的棕色狐狸跳过了懒狗。敏捷的棕色狐狸跳过懒惰的狗(见第 3 册)

我知道这个正则表达式sentence.replace(/ *\([^)]*\) */g, "");- 但我不知道如何应用上述条件。

标签: javascriptregexp-replace

解决方案


在这里,希望对你有帮助

const sentence = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit (see the Book "abc"). Quisque non ante nisi (see the Book "def"). Nam id justo velit (see above). Donec hendrerit dui sit amet tempus molestie (see the Book "ghi").'

console.log(sentence.replace(/\s?\([\w\s\"]*?Book[\w\s\"]*?\)\s?(?=..*\w)/gm, ''));

在这里你可以看到正则表达式的解释和实验 - https://regex101.com/r/hOZg0g/5


推荐阅读