javascriptregexregexp-replace

Remove dots and spaces from formatted numbers but leave them in the rest of the sentence


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?

Needs to be converted to.

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.


Solution

  • You can use

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

    See the regex demo.

    Details

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