How to check if a string contains a number in JavaScript?

前端 未结 8 1471
粉色の甜心
粉色の甜心 2021-01-13 18:37

I don\'t get how hard it is to discern a string containing a number from other strings in JavaScript.

Number(\'\') evaluates to 0, while

8条回答
  •  猫巷女王i
    2021-01-13 18:59

    A very short, wrong but correctable answer was just deleted. I just could comment it, besides it was very cool! So here the corrected term again:

    n!=='' && +n==n'
    

    seems good. The first term eliminates the empty string case, the second one enforces the string interpretataion of a number created by numeric interpretation of the string to match the string. As the string is not empty, any tolerated character like whitespaces are removed, so we check if they were present.

提交回复
热议问题