Javascript Data Type How to - Parse numbers from a string and push them to an array








Question

We would like to know how to parse numbers from a string and push them to an array.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--  w  w w  .  ja  va 2s  .  c o  m-->
var str, strArr, regex;
str = '5-2 7-1 8-9 7-4 1-3 1-0 2-8 8-0 6-9';
regex = new RegExp("-", 'g');
str = str.replace(regex, " ");
strArr = str.split(" ");
document.writeln(strArr);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: