user18713055
user18713055

Reputation: 21

Remove spaces before and after parentheses without using lookbehind

Im trying to remove the space after and before closing parenthesis using regex, the problem is that Safari not supporting my solution, is there any alternative for using "lookbehind" functionality?

My string for example: check IN [ "[hello world]*" ] OR host IN ( abc,123)

Im expecting to get: check IN ["[hello world]*"] OR host IN (abc,123)

My current solution: (?<=[([])\s+|\s+(?=[)\]])

Upvotes: 2

Views: 236

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Assuming:

  1. You always want to remove any spaces after a ( or [ and any spaces before a ) or a ], and

  2. You won't have (, ), [, or ] inside text literals that you want to leave unchanged (this is really just a subset of #1, but I thought it worth calling out specifically, as it's a big assumption)

...then I don't think nesting is an issue and we can do this with a regular expression. And I don't think you need lookaround at all:

const result = str.replace(/([\[(])\s+|\s+([\])])/g, "$1$2");
//                          ^^^^^^^^^^ ^^^^^^^^^^
// after opening ( or [ −−−−−−−−/          |
// before closing ) or ] −−−−−−−−−−−−−−−−−−/

The trick there is that we use two captures, and then use both in the replacement; one of them will always be "" while the other will be "(", "[", ")", or "]".

Example:

const str = `check IN [ "[hello world]*" ] OR host IN (  abc,123)`;

const result = str.replace(/([\[(])\s+|\s+([\])])/g, "$1$2");
//                          ^^^^^^^^^^ ^^^^^^^^^^
// after opening ( or [ −−−−−−−−/          |
// before closing ) or ] −−−−−−−−−−−−−−−−−−/

document.getElementById("before").textContent = str;
document.getElementById("result").textContent = result;
Before:
<pre id="before"></pre>
After:
<pre id="result"></pre>

Upvotes: 4

Related Questions