[英]Javascript Remove all charater except leading - , one dot and digits
首先這個問題與
我想轉換一個帶有有效數字的字符串,例如。
--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
-
(減號或連字符)不會造成任何問題,因為它的位置僅在數字之前而不是數字之間。 所以這可以使用以下正則表達式來解決。
正則表達式: -(?=-)|(?<=\\d)-(?=\\d+(-\\d+)?$)
並替換為empty
字符串。
然而,的位置.
(十進制)無法確定。 因為123.13.123
也可能意味着123.13123
和12313.123
。
如果沒有正則表達式,您可以通過這種方式映射字符:
// 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
將其格式化為正確的語言環境設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.