问题
I would like to remove one or more spaces before and after any parentheses. Following this post where the issue has been solved for PHP with the following regex
(?<=[([]) +| +(?=[)\]])
now I would like to do the same in Javascript but Javascript regex engine does not have the same lookahead and lookbehind as PHP. I managed to make the following regex at least work in Javascript but it removes all spaces:
?![([]) +| +(?=[)\]])
See Regex101 test.
Given string:
This is ( a sample ) [ string ] to play with
Expected result:
This is (a sample) [string] to play with
回答1:
You may use capturing groups instead and replace with their placeholders to restore the bracket/parentheses in the result:
.replace(/([([])\s+|\s+([)\]])/g, "$1$2");
See the regex demo
Details
([([])\s+- Group 1 capturing either a(or a[(referred to with$1from the string replacement pattern) and then 1+ whitespaces|- or\s+([)\]])- 1+ whitespaces followed with a)or]captured into Group 2 (referred to with$2from the string replacement pattern)
JS demo:
var strs = ['This is ( a sample ) [ string ] to play with',
'This is ( a sample ) [ string] to play with'];
var rx = /([([])\s+|\s+([)\]])/g;
for (var s of strs) {
console.log(s+ " =>\n"+ s.replace(rx, "$1$2"));
}
回答2:
You can try this:
function Do(){
console.log(document.querySelector("input").value
.replace(/\s*?\s([\[\(])\s*/g, " $1").replace(/\s*([\)\]])(\s?)\s*/g, "$1$2"));
}
<b>Type Your String Here:</b>
<input type='text' style='width:300px' value="This is ( a sample ) [ string ] to play with"/>
<input type='button' onclick="Do();" value="Start!"/>
回答3:
You achieve this by using Positive lookaheads and a simple replace.
.replace(/(?<=[\(|\[])\s+|\s+(?=[\]|\)])/g, '');
ex.
const currentString = 'This is ( a sample ) [ string ] to play with';
const regex = /(?<=[\(|\[])\s+|\s+(?=[\]|\)])/g;
console.log(currentString.replace(regex, ''));
来源:https://stackoverflow.com/questions/52188557/remove-all-spaces-before-and-after-parentheses