简体   繁体   English

删除字符串中除数字以外的所有内容

[英]Removing everything except numbers in a string

I've made a small calculator in javascript where users enter the interest rate and amount the they want to borrow, and it calculates how much of an incentive they might get.我用 javascript 制作了一个小型计算器,用户可以在其中输入利率和他们想借的金额,然后计算他们可能获得多少奖励。

The problem is that I'm worried users will enter symbols, eg问题是我担心用户会输入符号,例如

Loan amount: £360,000 - Interest Rate: 4.6%贷款金额:360,000 英镑 - 利率:4.6%

I'm not worried about the decimal places as these are needed and don't seem to affect the calculation, it's the symbols like £ and % which mess things up.我不担心小数位,因为这些是必需的,而且似乎不会影响计算,而是像 £ 和 % 这样的符号把事情搞砸了。

Is there a simple way to strip out these symbols from the code:有没有一种简单的方法可以从代码中去除这些符号:

<td><input type="text" name="loan_amt" style="background-color:#FFF380;"></td>
<td><input type="text" name="interest_rate" style="background-color:#FFF380;"></td>


function Calculate()
{
    var loan_amt = document.getElementById('loan_amt').value;
    //this is how i get the loan amount entered
    var interest_rate = document.getElementById('interest_rate').value; 
    //this is how i get the interest rate

    alert (interest_rate);
}

Note that you should use the correct DOM id to refer via getElementById.请注意,您应该使用正确的 DOM id 通过 getElementById 进行引用。 You can use the .replace() method for that:您可以使用.replace()方法:

var loan_amt = document.getElementById('loan_amt');
loan_amt.value = loan_amt.value.replace(/[^0-9]/g, '');

But that will remove float point delimiter too.但这也会删除浮点分隔符。 This is an answer to your question, but not a solution for your problem.这是对您问题的回答,但不是您问题的解决方案。 To parse the user input as a number, you can use parseFloat() - I think that it will be more appropriate.要将用户输入解析为数字,您可以使用parseFloat() - 我认为它会更合适。

这是最短的:

replace(/\D/g,'');

Here is my solution:这是我的解决方案:

const filterNum = (str) => {
  const numericalChar = new Set([ ".",",","0","1","2","3","4","5","6","7","8","9" ]);
  str = str.split("").filter(char => numericalChar.has(char)).join("");
  return str;
}

console.log(filterNum("143.33$"));
// 143.33

there is very good plugin you can use it.有非常好的插件你可以使用它。 For example例如

//include jQuery.js and autoNumeric-1.8.3.js javascript files in the header. //在标题中包含 jQuery.js 和 autoNumeric-1.8.3.js javascript 文件。

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
    <script src="autoNumeric-1.8.0.js" type=text/javascript> </script>

  // this example uses the id selector & no options passed    
  jQuery(function($) {
      $('#someID_defaults').autoNumeric('init');    
  });

see check below http://www.decorplanit.com/plugin/请参阅下面的检查http://www.decorplanit.com/plugin/

You should probably test for and reject invalid values but if you have to clean a dodgy string into a number then this should work:您可能应该测试并拒绝无效值,但是如果您必须将狡猾的字符串清理成一个数字,那么这应该有效:

var inStr = "a12ab.c34...h.re567";
var justOneDot = inStr.replace(/[.](?=.*?\.)/g, '');//look-ahead to replace all but last dot
var outStr = parseFloat(justOneDot.replace(/[^0-9.]/g,'')).toFixed(2); //parse as float and round to 2dp 
// = 1234.57

Play with it in this JS Bin .这个 JS Bin 中使用它。

try this试试这个

Eg:例如:

var a="4.52%"
var stringLength = a.length;
var lastChar = a.charAt(stringLength - 1); 

if(lastChar.match(/[^\w\s]/)) {
    a=a.substring(0,stringLength - 1);
}

alert(a);

Now you can typecast to number现在您可以将类型转换为数字

Did the function to remove all but floats.执行删除除浮动以外的所有内容的功能。 Double dot is not possible.双点是不可能的。

inspired by the solution of JulienRioux灵感来自于 JulienRioux 的解决方案

function removeAllButFloatFromInput(input, floatAmount) {
  $(input).on("input change paste", ({ target }) => {
    let { value } = target
    let allowedChars = [".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    let newValArr = value.split("").filter(char => allowedChars.includes(char)).join("").split(".")
    let newValStr = ""

    if (newValArr.length == 1) {
      newValStr = newValArr[0]
    } else if (newValArr.length == 2 && floatAmount !== undefined) {
      newValArr[1] = newValArr[1].substr(0, floatAmount)
      newValStr = newValArr.join(".")
    } else if (newValArr.length == 2) {
      newValStr = newValArr.join(".")
    } else if (floatAmount !== undefined) {
      newValStr = newValArr[0] + "." + newValArr.splice(1).join("").substr(0, floatAmount)
    } else {
      newValStr = newValArr[0] + "." + newValArr.splice(1).join("")
    }

    target.value = newValStr
  })

  if (!!floatAmount) {
    $(input).on("blur", ({ target }) => {
      if (!!target.value) {
        target.value = parseFloat(target.value).toFixed(floatAmount)
      } else {
        target.value = parseFloat(0).toFixed(floatAmount)
      }
    })
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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