Javascript删除除前导字符、单点字符和数字以外的所有字符

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

本文关键字:字符 数字 单点 删除 Javascript      更新时间:2023-10-20

首先,这个问题与不同

从字符串或中删除非数字字符

Regex替换除数字和小数点之外的所有内容

我想转换一个具有有效数字的字符串,如。

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

我试过那些

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

我正面临前导减号的问题。

如何转换一个字符串,该字符串将删除除前导-(删除其他减号)、数字和仅一个点(删除其他点)之外的所有字符

我在这里分享我的解决方案
假设字符串为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, '');

更新浮点数。(解决复制粘贴问题)

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

基于@Shaiful Islam的回答,我又添加了一个代码。

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.

结果

00.434 => 0.434

不是很干净,但有效!

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

在下面给出的样本数据中,

--1234
-123-123
12.123.3
-123.13.123

-(减号或连字符)不会造成问题,因为它的位置仅在数字前,而不在数字之间。因此,可以使用以下正则表达式来解决此问题。

Regex:-(?=-)|(?<='d)-(?='d+(-'d+)?$)并替换为empty字符串。

Regex101演示

但是,无法确定.(十进制)的位置。因为CCD_ 8也可以表示CCD_ 9和CCD_。

如果没有regex,您可以通过以下方式映射字符:

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

希望能有所帮助。

我的解决方案:

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

然后应该使用Intl.NumberFormat将其格式化为正确的区域设置。

相关文章: