简体   繁体   English

如果JavaScript中的第一个字符不是数字,如何从字符串中删除呢?

[英]How to remove the first character from a string if it's a non-number in JavaScript?

I have a text field on a form that allows individuals to enter a price. 我在表格上有一个文本字段,允许个人输入价格。 I'm trying to allow other currency symbols to be entered into this field but my logic behind the scenes needs to strip out any currency symbols. 我试图允许在该字段中输入其他货币符号,但是我的幕后逻辑需要删除所有货币符号。

To make it easier, I really only care about the first character and only if it's a non number. 为了简化起见,我真的只关心第一个字符,并且只有第一个字符不是。

Otherwise, I can't use a solution that would remove any decimal points or commas in my price field or my calculations won't work. 否则,我将无法使用一种解决方案来删除价格字段中的任何小数点或逗号,否则我的计算将无法进行。

Update: I'm currently using itemCost = itemCost.replace(/\\$/, ''); 更新:我当前正在使用itemCost = itemCost.replace(/ \\ $ /,'');

But now I'm trying to open it up to any currency sign. 但是现在我正尝试将其开放给任何货币符号。

You can access a string in the same way as you would an array. 您可以使用与数组相同的方式访问字符串。 Take a look at the character at position zero of the string - 看一下字符串零位置处的字符-

var inputString = '...' // whatever the user entered
var firstChar = inputString[0];
if (!Number.isInteger(firstChar)) {
    inputString = inputString.substr(1)
}

I'm using the String.subStr function here to create a copy of the string starting from the 1st index. 我在这里使用String.subStr函数从第一个索引开始创建字符串的副本。

Please take into consideration though that solution assumes that the provided string will only ever have one currency symbol. 请注意,尽管该解决方案假定提供的字符串将包含一个货币符号。 Inputs such as "USD $1.00" or even " $1.00" will not work with this solution. 此解决方案无法使用“ USD $ 1.00”甚至“ $ 1.00”之类的输入。


An alternative would be to remove any character that is non numeric (excluding decimal points and commas) from the entire input string. 一种替代方法是从整个输入字符串中删除所有非数字字符(小数点和逗号除外)。

var inputString = '...' // whatever the user entered
var priceString = inputString.replace(/[^0-9\.,]/, '')

// $1.00 -> 1.00
// USD #$1,000.00 -> 1,000.00

Why don't you whitelist characters instead? 您为什么不将字符列入白名单?

'$99,99'.match(/[0-9]+[,.]{0,1}[0-9]*/)

You'll certainly want to perfect it, I wrote it fast... 您肯定会想完善它,我写得很快。

What the suggested regex does is make sure we have one or more digits, then maybe either a , or a . 有什么建议的正则表达式的作用是确保我们有一个或多个数字,那么也许无论是,还是一个. and 0 or more digits. 和0或更多数字。

What I mostly want to point out with this answer is, while keeping just numeric characters is easy, it will by no mean make certain that the user entered a correct currency. 我最想指出的是,虽然仅保留数字字符很容易,但绝不能确保用户输入了正确的货币。 The is also no way to know if the user entering 1,337 meant 1,337.00 or 1.337 也无法知道用户输入1,3371,337.00还是1.337

You may use parseInt() 您可以使用parseInt()

parseInt() parses a string and returns an integer. parseInt()解析字符串并返回整数。

If the first character cannot be converted to a number , parseInt() returns NaN . 如果第一个字符不能转换为数字 ,则parseInt()返回NaN

parseInt('Hello') // returns NaN

Also it's a good idea to trim() the string before using parseInt() 另外,在使用parseInt()之前先trim()字符串是一个好主意。

 var money = '$123.45'; if( money ) { // check if variable is not null money = money.trim(); } console.log(parseInt(money)); // check NaN using isNaN function if(isNaN(parseInt(money))) { console.log('first charatcer is not a number') money = money.substr(1); console.log(money); } else { console.log('first charatcer is a number') } 

A Javscript function could be Javscript函数可能是

// Function to check first letter as numbers //检查第一个字母为数字的函数

function chkNumeric(inputtxt)  
{

 var letterNumber = '^[0-9]{1,}[ a-zA-Z0-9]*$';  

 if((inputtxt.value.match(letterNumber))   
  {  

   return true;  

  }  

else  

  {   
   return false;   

  }  

  }

There's a few ways you can do this... One way is to make the input into an array, check isNaN on the first element, and strip it if it's not a number. 有几种方法可以执行此操作...一种方法是将输入输入到数组中,检查第一个元素上的isNaN,如果不是数字则将其剥离。

const input = '$123.45';
const otherInput = '23.34';


function splitCheck(someInput) {
  let arrayInput = someInput.split('');
  if (isNaN(arrayInput[0])) {
      arrayInput.shift();
      return arrayInput.join('');
  } else {
      return someInput;
  }
}

splitCheck(input); // returns 123.45
splitCheck(otherInput); // returns 23.34

Note you can also use a regexp, or you can also check for ASCII character values across an array, but this is just the first that came to mind. 请注意,您也可以使用正则表达式,也可以在整个数组中检查ASCII字符值,但这只是我第一次想到。

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

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