+myString.replace(/[^\d.ex-]+/gi, '')
strips out all characters that cannot appear in a JavaScript number, and then applies the +
operator to it to convert it to a number. If you don't have numbers in hex format or exponential format then you can do without the ex
.
EDIT:
To handle locales, and handle numbers in a more tailored way, I would do the following
// Get rid of myriad separators and normalize the fraction separator.
if ((0.5).toLocaleString().indexOf(',') >= 0) {
myString = myString.replace(/\./g, '').replace(/,/g, '.');
} else {
myString = myString.replace(/,/g, '');
}
var numericValue = +(myString.match(
// Matches JavaScript number literals excluding octal.
/[+-]?(?:(?:(?:0|[1-9]\d*)(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|0x[0-9a-f]+)/i)
// Will produce NaN if there's no match.
|| NaN);