bflemi3 bflemi3 - 8 days ago 6
Javascript Question

Regex to remove space after first parenthesis and before last parenthesis

I need to remove the space after the first parenthesis and the space before the last parenthesis of the following strings:

POINT ( -68.1712366598 -16.5122344611 4124.6247727228 )
POINT ( -68.1712366598 -16.5122344611 )
POINT Z ( -68.1712366598 -16.5122344611 4124.6247727228 )
POINT Z ( -68.1712366598 -16.5122344611 )


The results would be:

POINT (-68.1712366598 -16.5122344611 4124.6247727228)
POINT (-68.1712366598 -16.5122344611)
POINT Z (-68.1712366598 -16.5122344611 4124.6247727228)
POINT Z (-68.1712366598 -16.5122344611)


I can get the first space but having issues with the last space.

^\w*\s*\((\s*)


Please see regex101 for my attempt

Answer

Just .replace(/\(\s*(.*?)\s*\)/,"($1)"))

The idea is to use a non greedy capture, .*?, to capture what's between the two parts to replace.

Demonstration:

document.getElementById("output").innerHTML = document.getElementById("input")
  .innerHTML.split("\n")
  .map(line=>line.replace(/\(\s*(.*?)\s*\)/,"($1)"))
  .join("\n");
<pre id=input>
POINT ( -68.1712366598 -16.5122344611 4124.6247727228 )
POINT ( -68.1712366598 -16.5122344611 )
POINT Z ( -68.1712366598 -16.5122344611 4124.6247727228 )
POINT Z ( -68.1712366598 -16.5122344611 )
</pre>
<pre id=output>
</pre>