7

First of all this question is not same as

strip non-numeric characters from string or

Regex to replace everything except numbers and a decimal point

I want to convert a string with valid number like.

--1234// will be -1234
-123-123 will be -123123
12.123.3 will be 12.1233
-123.13.123 will be -123.13123

I tried those

number.replace(/[^0-9.-]/g, '') //it accepts multiple . and -
number.replace(/[^0-9.]-/g, '').replace(/(\..*)\./g, '$1');//it accepts multiple minus

I am facing Problem with leading minus sign.

How I can convert a string which will remove all characters except leading -(remove other minus),digits and only one dot(remove other dots)

Community
  • 1
  • 1
Shaiful Islam
  • 7,034
  • 12
  • 38
  • 58
  • 2
    I don't think you can do this with regex, you are applying logic to your matches. For instance, you want to concatenate different groups of numbers into one discarding some characters in the middle. Regex is not the tool for doing this. – Federico Piazza Mar 30 '16 at 23:34
  • @FedericoPiazza I am almost there.Can you help me to write the regex to find all -(minus sign) except first one. – Shaiful Islam Mar 30 '16 at 23:40
  • @ShaifulIslam: I came up with solution to solve the -(minus sign) problem. But `.(decimal)` position cannot be defined by simple rule. Check my answer for explanation. –  Mar 30 '16 at 23:42
  • @ShaifulIslam, see if my answer helps you. – hallucinations Mar 31 '16 at 00:01

6 Answers6

7

Here I am sharing my solution.
Lets assume the string is a;

//this will convert a to positive integer number
b=a.replace(/[^0-9]/g, '');

//this will convert a to integer number(positive and negative)
b=a.replace(/[^0-9-]/g, '').replace(/(?!^)-/g, '');

//this will convert a to positive float number

b=a.replace(/[^0-9.]/g, '').replace(/(..*)./g, '$1');

//this will convert a to float number (positive and negative)

b=a.replace(/[^0-9.-]/g, '').replace(/(..*)./g, '$1').replace(/(?!^)-/g, '');

Update for floating number.(solves copy paste problem)

//For positive float number
b=a.replace(/[^0-9.]/g, '').replace('.', 'x').replace(/\./g,'').replace('x','.');

//For Negative float number
b=a.replace(/[^0-9.-]/g, '').replace('.', 'x').replace(/\./g,'').replace('x','.').replace(/(?!^)-/g, '');
Community
  • 1
  • 1
Shaiful Islam
  • 7,034
  • 12
  • 38
  • 58
6

Based on @Shaiful Islam's answer, I added one more code.

var value = number
    .replace(/[^0-9.-]/g, '')       // remove chars except number, hyphen, point. 
    .replace(/(\..*)\./g, '$1')     // remove multiple points.
    .replace(/(?!^)-/g, '')         // remove middle hyphen.
    .replace(/^0+(\d)/gm, '$1');    // remove multiple leading zeros. <-- I added this.

Result

00.434 => 0.434
wonsuc
  • 3,498
  • 1
  • 27
  • 30
3

Not very clean, but works!

var strings = ["-1234","-123-123","12.123.3", "-123.13.123"];
strings.forEach(function(s) {
    var i = 0;
    s = s.replace(/(?!^)-/g, '').replace(/\./g, function(match) { 
        return match === "." ? (i++ === 0 ? '.' : '') : ''; 
    });
    console.log(s);
});
hallucinations
  • 3,424
  • 2
  • 16
  • 23
0

In your sample data given below,

--1234
-123-123
12.123.3
-123.13.123

-(minus sign or hyphen) causes no problem because it's place is only before digits and not between digits. So this can be solved using following regex.

Regex: -(?=-)|(?<=\d)-(?=\d+(-\d+)?$) and replace with empty string.

Regex101 Demo

However, the position of .(decimal) cannot be determined. Because 123.13.123 could also mean 123.13123 and 12313.123.

0

Without regex, you can map over the characters this way:

// this function takes in one string and return one integer
f=s=>(
    o='',                   // stands for (o)utput
    d=m=p=0,                // flags for: (d)igit, (m)inus, (p)oint
    [...s].map(x=>          // for each (x)char in (s)tring
        x>='0'&x<='9'?      // if is number
            o+=x            // add to `o`
        :x=='-'?            // else if is minus
            m||(p=0,m=o=x)  // only if is the first, reset: o='-';
        :x=='.'?            // else if is point
            p||(p=o+=x)     // add only if is the first point after the first minus
        :0),                // else do nothing
    +o                      // return parseInt(output);
);

['--1234','-123-123','12.123.3','-123.13.123'].forEach(
x=>document.body.innerHTML+='<pre>f(\''+x+'\') -> '+f(x)+'</pre>')

Hope it helps.

0

My solution:

number.replace(/[^\d|.-]/g, '') //removes all character except of digits, dot and hypen
      .replace(/(?!^)-/g, '') //removes every hypen except of first position
      .replace(/(\.){2,}/g, '$1') //removes every multiplied dot

It should then formatted to the proper locale setting using Intl.NumberFormat.

Jsowa
  • 9,104
  • 5
  • 56
  • 60