Skip to content Skip to sidebar Skip to footer

Remove All Spaces Before And After Parentheses

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 (?<=[([]) +| +(?

Solution 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 $1 from the string replacement pattern) and then 1+ whitespaces
  • | - or
  • \s+([)\]]) - 1+ whitespaces followed with a ) or ] captured into Group 2 (referred to with $2 from 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"));
}

Solution 2:

You can try this:

functionDo(){
    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><inputtype='text'style='width:300px'value="This is   (    a sample  )    [         string  ]   to play with"/><inputtype='button'onclick="Do();"value="Start!"/>

Solution 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, ''));

Post a Comment for "Remove All Spaces Before And After Parentheses"