I keep getting undefined function error at nums.match(). I have tried other methods as well, to no success.
I want to create a general function in javascript that will extract all numbers from a random string and add them into an array, in the order of extraction. Any Idea why I keep getting this error?
Uncaught TypeError: undefined is not a function
Here is my current function:
var nums="A rectangle measuring 30.0 cm by 40.0 cm is located inside a region of a spatially uniform magnetic field of 1.35T , with the field perpendicular to the plane of the coil. The coil is pulled out at a steady rate of 2.00 cm/s traveling perpendicular to the field lines. The region of the field ends abruptly as shown.";
nums = nums.match(/\d+\.?\d*/g);
alert(nums);
var bookNums = nums.split(" ");
alert(bookNums[0],bookNums[1],bookNums[2]);
After the assignment in your second line of code, nums
is an array not a string. There is no Array.prototype.split
, which is causing your error. Because String.prototype.match
returns an array, nums
already contains the values you want (or null
if no matches were found).
Here's a rewrite that should work:
var nums = "A rectangle measuring 30.0 cm by 40.0 cm is located inside a region of a spatially uniform magnetic field of 1.35T , with the field perpendicular to the plane of the coil. The coil is pulled out at a steady rate of 2.00 cm/s traveling perpendicular to the field lines. The region of the field ends abruptly as shown.";
var bookNums = nums.match(/\d+\.?\d*/g);
console.log(bookNums); // array or null
var nums="A rectangle measuring 30.0 cm by 40.0 cm is located inside a region of a spatially uniform magnetic field of 1.35T , with the field perpendicular to the plane of the coil. The coil is pulled out at a steady rate of 2.00 cm/s traveling perpendicular to the field lines. The region of the field ends abruptly as shown.";
var nums_array = nums.match(/\d+\.?\d*/g);
var bookNums = nums_array;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.