Skip to content
Advertisement

Javascript Regex remove spaces around dash in numbers but not strings

I’m trying to remove spaces around dashes in a string, but only when within numbers:

10 - 89 - 90 should become 10-89-90.

But when within a string, they should keep the spaces:

A - Z should remain A - Z. As well as 90 - older should stay 90 - older.

So only when there are numbers on both sides of the dash, should the spaces be removed.

I tried this:

item = item.replace(/(d) - (d)/g, "$1-$2");

But nothing happened.

Edit: My dashes were indeed being turned into em dashes by Excel, but I accepted the answer since it does anticipate an issue I could very well run into (having only one digit in between dashes).

Advertisement

Answer

Using (d) - (d) will work for 10 - 89 - 90 but it will not work for 10 - 8 - 9 as the single digit in the second d is already matched.

There also must be at least a single space at the left and at the right of each digit, which would also not match the last space in 10 - 89 -90

You can use

b(d+)s*-s*(?=d+b)
  • b(d+) A word boundary, capture 1+ digits
  • s*-s* Match a hyphen between optional whitespace chars
  • (?=d+b) Positive lookahead, assert 1+ digits followed by a word boundary

And replace with

$1-

Regex demo

[
  "0 - 89 - 90",
  "90 - older"
].forEach(
  item => console.log(item.replace(/b(d+)s*-s*(?=d)/g, "$1-"))
)

When the quantifier in the lookbehind is supported:

[
  "0 - 89 - 90",
  "90 - older"
].forEach(
  item => console.log(item.replace(/(?<=bd+)s*-s*(?=d+b)/g, "-"))
)
Advertisement