This question has already been answered:

There is a string

"!(31310" 

How to convert it to number?

 parseInt(), new Number(), valueOf() - не подходят 

Reported as a duplicate by Grundy , aleksandr barakin , user194374, Bald , VenZell July 7 '16 at 8:54 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • remove extra characters to start with - Bogdan Gudyma
  • This is the essence of my question. How to convert a string if at the beginning there are characters. If I remove the extra characters, this is almost a ready-made solution. - user190134
  • Can there be a real number in the string? - ampawd

2 answers 2

like so

 var string = "!(31310"; var number = +(string.match(/\d+/g)); console.log(typeof number); console.log(number); 

what it does, match collects all the numbers into an array and stitches the array with join, and with + we convert the value from the String type to the Number type

  • you can at least replace the regular schedule with \d+ , and remove join - Grundy
  • I may not be very strong in regulars :) - pnp2000

for integers, the solution is for example:

 function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function getIntFromString(str) { var str_num = ""; var i = 0; while (i < str.length && !isNumeric(str[i]) && str[i] !== '-') { i++; } if (str[i] === '-') { str_num += '-'; } i = 0; while (i < str.length) { str_num += isNumeric(str[i]) ? str[i] : ''; ++i; } return parseInt(str_num); } var str = "!(31310"; var num = getIntFromString(str); alert(typeof num); alert(num);