簡體   English   中英

Javascript正則表達式只允許數字和浮點數

[英]Javascript regex allow only number and float

我有以下代碼用於替換字符串中除數字/浮點數之外的任何內容。

const parseNumbers = strInput => strInput
  .trim()
  .replace(/^[@#$%^&*()_+}{|{}[\]/<>,.;'"`~a-z!]*/gi, '')
  .replace(/[^0-9]+[.][0-9]*/g, "");

以下字符串不適用於上述正則表達式:

'644322.abc'

雖然這有效'644322.abc .....'被轉換為644322

'644322.12ac .....'被轉換為644322.12

但這不會:

'644322.12ac'被轉換為644322.12ac

'644322.12-1'保持原樣644322.12-1

我想替換所有不是數字的字符並將值保留為數字或浮點數。

你能舉個例子嗎? 這是根據你的問題提出的。

 let input = "I have below code for replace anything apart from number/ float from a string.The following strings are not working with the above regex:'644322.abc'While this works '644322.abc.....' gets converted to 644322'644322.12ac.....' gets converts to 644322.12But this does not:'644322.12ac' gets converted to 644322.12ac'644322.12-1' remains as is 644322.12-1" let re = /[+-]?([0-9]*[.])?[0-9]+/g let m = input.match(re); console.log(m)

您可以先刪除除數字和點以外的所有字符,然后刪除除第一個以外的所有點(除非第一個點位於字符串的末尾)並使用

 const texts = ['644322.abc', '644322.12ac.....', '644322.12ac', '644322.12-1']; texts.forEach( text => console.log( text, '=>', text.replace(/[^\\d.]+/g, '').replace(/^([^.]*\\.)(?!$)|\\./g, '$1') ))

詳情

  • .replace(/[^\\d.]+/g, '') - 刪除除數字和點以外的所有字符
  • .replace(/^([^.]*\\.)(?!$)|\\./g, '$1') - 刪除除第一個不在字符串末尾的點以外的所有點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM