javascript - 使用正则表达式删除括号和其中的文本,无需额外的剩余空格

标签 javascript regex

我想删除给定字符串中的 [] 符号及其内部的任何内容:

const text = "This should [but this should be removed with the brackets] stay intact."

const result = text.replace(/\[.*?\]/g,'')

console.log(result);

问题是删除括号后剩余的多余空间。

我该如何解决这个问题?

最佳答案

我可以选择匹配模式两侧的空格,然后替换为单个空格:

const text = "This should [but this should be removed with the brackets] stay intact."

const result = text.replace(/ ?\[[^\]]*\] ?/g,' ')

console.log(result);

关于javascript - 使用正则表达式删除括号和其中的文本,无需额外的剩余空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65382483/

相关文章:

javascript - 创建 window.AddEventListener 时 Div 不显示到 'none'

java - 是否可以自动获取 Intellij 对自己的正则表达式参数的正则表达式帮助

python - 用于查找行为奇怪的回文的正则表达式

c++ - 在 Eclipse 中将 Boost 链接到我的 C++ 项目

javascript - 我想在 codeigniter 中禁用 datetimepicker 中的过去时间

javascript - 如何将上传的图像添加到对象数组中?

javascript - visual studio 隐藏了 .js.map 文件和 .js 文件,只显示了 typescript .ts 文件,

javascript - Ext JS 4.2 底漆

javascript正则表达式匹配多行

r 中的正则表达式模式问题