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

霸气de小男生 提交于 2021-02-16 13:14:36

问题


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)


回答1:


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



回答2:


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



回答3:


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



回答4:


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.




回答5:


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.




回答6:


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.



来源:https://stackoverflow.com/questions/36321409/javascript-remove-all-charater-except-leading-one-dot-and-digits

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!