Javascript 从变量中删除括号和尾随空格
删除括号和任何(但仅限于)尾随空格的好正则表达式是什么Javascript 从变量中删除括号和尾随空格,javascript,regex,Javascript,Regex,删除括号和任何(但仅限于)尾随空格的好正则表达式是什么 示例:“Hello[world]-这是什么?”将转换为“Hello-这是什么?”您可以这样做: var result = mystring.replace(/^\s*\[[^]]+]\s*|\s*\[[^]]+]\s*$|(\s)\s*\[[^]]+]\s*/g, '$1'); 可以让表达式在括号内的内容和尾随空格之间交替: str.replace(/\[[^\]]*\]|\s+$/g, '') /g修饰符用于匹配所有引用,而不是仅匹配
示例:
“Hello[world]-这是什么?”
将转换为“Hello-这是什么?”
您可以这样做:
var result = mystring.replace(/^\s*\[[^]]+]\s*|\s*\[[^]]+]\s*$|(\s)\s*\[[^]]+]\s*/g, '$1');
可以让表达式在括号内的内容和尾随空格之间交替:
str.replace(/\[[^\]]*\]|\s+$/g, '')
/g
修饰符用于匹配所有引用,而不是仅匹配第一个引用(默认值)
更新
如果[hello]
前面有一个空格,则该空格不会被删除,您需要另一个.replace()
而不是替换:
str.replace(/\[[^\]]*\]/g, '').replace(/\s+$/, '');
使用下面的正则表达式。它将删除括号及其尾随空格
/(\s\s)*(\s(?=\[.*?\]\s))*\[.*?\](\s\s)*/g
用法:
var testStr = "Hello [world] - what is this?";
console.log(testStr.replace(/(\s\s)*(\s(?=\[.*?\]\s))*\[.*?\](\s\s)*/g, ""));
输入/输出:
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world]- what is this? Output: Hello - what is this?
Input: Hello [world]- what is this? Output: Hello - what is this?
Input: Hello[world] - what is this? Output: Hello - what is this?
Input: Hello[world] - what is this? Output: Hello - what is this?
Input: Hello[world]- what is this? Output: Hello- what is this?
你是说括号里的词?或者任何以
[
开头并以]
结尾的内容。到目前为止你做了什么?(+1)最简单、最优化的我想他指的是在方括号后,而不是在括号的末尾加上空格string@acdcjunior我想你的意思是最后一个括号内的表达式之前的空格没有被删除?是的,刚刚注意到了,并修复了。@simonzack好吧,我想这有点可以解释:)就是这样-其他人删除了括号中的前导空格和尾随空格,或者保留空格不变-谢谢!
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world] - what is this? Output: Hello - what is this?
Input: Hello [world]- what is this? Output: Hello - what is this?
Input: Hello [world]- what is this? Output: Hello - what is this?
Input: Hello[world] - what is this? Output: Hello - what is this?
Input: Hello[world] - what is this? Output: Hello - what is this?
Input: Hello[world]- what is this? Output: Hello- what is this?