Remove dots and spaces from strings

Tags: , ,



I want to remove dots . and spaces with regex text.replace(/[ .]+/g, '').

This is an 8-string 12.34.5678; and this is another 13-string 1234 5678 9123 0 okay?

But the main problem is that it removes all dots and spaces, from the sentence.

Thisisan8-string12345678;andthisisanother13-string1234567891230okay?

  • an 8-string 12.34.5678
  • another 13-string 1234 5678 9123 0

Needs to be converted to.

  • an 8-string 12345678
  • another 13-string 1234567891230

So the sentence will be:

This is an 8-string 12345678; and this is another 13-string 1234567891230 okay?

What am I doing wrong? Im stuck with finding/matching the right solution.

Answer

You can use

s.replace(/(d)[s.]+(?=d)/g, '$1')
s.replace(/(?<=d)[s.]+(?=d)/g, '')

See the regex demo.

Details

  • (d) – Group 1 ($1 in the replacement pattern is the value of the group): a digit
  • [s.]+ – one or more whitespace or . chars
  • (?=d) – a positive lookahead that ensures the next char is a digit.

See JavaScript demo:

const text = 'This is an 8-string 12.34.5678; and this is another 13-string 1234 5678 9123 0 okay?';
console.log(text.replace(/(d)[s.]+(?=d)/g, '$1'));


Source: stackoverflow