简体   繁体   中英

Javascript Remove all charater except leading - , one dot and digits

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)

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

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

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

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 .

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM