Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

reactjs - Javascript check if an string is a valid number

What is the correct way to check if a string is valid number in javascript?

Normally we use isNaN(str), this works great in all cases but excepts,

Current behaviour:

isNaN("1") = false, is a number,
isNaN("1 ") = false, But this is a string.

What is the correct approach to deal with this?

Expected results:

isNotNumber("1") = false
isNotNumber("1 ") = true
question from:https://stackoverflow.com/questions/65843474/javascript-check-if-an-string-is-a-valid-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's a bit of an odd case. I don't know of any native JS solution for this, but you could do the following:

function isNotNumber(subj: string): boolean {
  const nr = +subj;
  
  return isNaN(nr) || nr.toString().length !== subj.length;
}

example with tests


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...