0

I faced some problems with regex; I want to leave only valid numbers in a string, people might enter:

  1. 11.2.2

  2. abd11,asd11

and so on,

str = .replace(/[^[0-9]{1,2}([.][0-9]{1,2})?$]/g, '');

So I need to allow only digits and one dot from anything the user has entered;

This answer however doesn't work when I try to put it in:

str.replace(/(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )/,'');

It gives me a JS error. Please help me to understand what am I doing wrong.

p.s: thank You all guys for helping me, i found solution HERE, so i think thread may be closed.

Community
  • 1
  • 1
ailmcm
  • 373
  • 1
  • 5
  • 15

3 Answers3

1

use regex as

\d*[0-9]\.\d*[0-9]
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
0

You must use quotes. Like this:

str.replace("/(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )/",'');
Norbert
  • 302
  • 1
  • 9
  • 19
0

How about:

/(?: |^)\d*\.?\d+(?: |$)/

this will match:

12
12.34
.34
Toto
  • 89,455
  • 62
  • 89
  • 125