繁体   English   中英

Javascript Regex:如何删除某些字符周围的所有空格?

[英]Javascript Regex: How to remove all whitespaces around certain character?

可能我做错了,我找到了一个正则表达式来实现PHPC#中所需的替换,但是将它应用于javascript失败了。

例:

text ( 4 |-4 | 1 "test" ) [ 0 50 90 ]

应该清理到:

text(4|-4|1 "test")[0 50 90]

如您所见,我删除了括号和|之前和之后的所有空格。

我的代码到目前为止:

        // remove whitespaces around brackets []
        text = text.replace(/\s*\[\s*(.*?)\s*]\s*/g, '[$1]');
        // remove whitespaces around brackets ()
        text = text.replace(/\s*\(\s*(.*?)\s*\)\s*/g, '($1)');
        // remove all whitespaces around | (FAILS)
        // text = text.replace(/\s*\|\s*(.*?)\s*\|\s*/g, '|$1|');
        // text = text.replace(/\s*|\s*/, '$1');

看起来也太复杂了。

我想知道每个标志的正则表达式。

并非所有替代品都在一个正则表达式中,因为学习我更希望每行更换一次。

这样就可以了:

 var text = 'text ( 4 |-4 | 1 "test" ) [ 0 50 90 ]'; text = text.replace(/\\s*([|()[\\]])\\s*/g, '$1'); alert(text) 

这个正则表达式查找(可选)空格,然后,在一个capature组中,一个不能有边界空格的字符,然后是另一个可选的空格,并用所有字符替换所有这些空格,有效地删除空格。


现在,如果要将替换放在单独的行上,并且只替换空格字符,保留其他空格不变,请尝试以下操作:

 var text = 'text ( 4 |-4 | 1 "test" ) [ 0 50 90 ]'; text = text.replace(/ *([|]) */g, '$1') .replace(/ *([(]) */g, '$1') .replace(/ *([)]) */g, '$1') .replace(/ *([[]) */g, '$1') .replace(/ *([\\]]) */g, '$1'); alert(text) 

或这个:

 var text = 'text ( 4 |-4 | 1 "test" ) [ 0 50 90 ]'; text = text.replace(/ *(|) */g, '$1') .replace(/ *(\\() */g, '$1') .replace(/ *(\\)) */g, '$1') .replace(/ *(\\[) */g, '$1') .replace(/ *(\\]) */g, '$1'); alert(text) 

对于单个字符,字符类有点矫枉过正,但是你需要转义()[] (就像我在最后一个片段中所做的那样)

诀窍是正确地逃避保留的字符,所以单个[成为\\[等等。 管道也是保留字符,因此您需要执行相同的操作:

 var example = "text ( 4 |-4 | 1 \\"test\\" ) [ 0 50 90 ]"; example = example.replace(/\\s*([\\(\\)])\\s*/g, '$1')); // removes the () example = example.replace(/\\s*([\\[\\]])\\s*/g, '$1')); // removes the [] example = example.replace(/\\s*([\\|])\\s*/g, '$1')); // removes the | // or remove all characters at once example = example.replace(/\\s*([\\(\\)\\[\\]\\|])\\s*/g, '$1') alert(example) 

暂无
暂无

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

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