Highcharts Maps小数数据匹配问题:正则表达式报错求助
Hey there, let's work through this regex problem you're hitting while reproducing that Highcharts example!
You mentioned your new World Bank life expectancy data includes values with 13 decimal places, and the existing regex numRegex = /^[0-9.]+$/ is breaking your code. That makes total sense—here's why and how to fix it:
What's Wrong with the Original Regex?
The original /^[0-9.]+$/ has two key flaws for your use case:
- It allows multiple decimal points (like
72.34.56), which isn't a valid numeric format - It doesn't enforce any structure on the decimal portion, which can lead to parsing unexpected, invalid values
Updated Regex for 13-Decimal Data
For your data with up to 13 decimal places, swap in this regex instead:
numRegex = /^\d+(\.\d{1,13})?$/
Quick Breakdown of the Regex:
^→ Anchors the match to the start of the string\d+→ Matches one or more digits (the integer part of your number)(\.\d{1,13})?→ An optional decimal section:\.→ Matches exactly one decimal point\d{1,13}→ Matches between 1 and 13 digits (perfect for your 13-decimal data)?→ Makes the entire decimal section optional (so it still works if some entries are integers)
$→ Anchors the match to the end of the string
If you don't need to strictly cap decimal places at 13 (just want to allow any valid decimal number), use this more flexible version:
numRegex = /^\d+(\.\d+)?$/
Extra Tip for Robust Parsing
After validating with the regex, convert the string value to a number using parseFloat() to ensure Highcharts can interpret it correctly:
if (numRegex.test(yourDataPoint)) { const numericValue = parseFloat(yourDataPoint); // Use numericValue in your Highcharts configuration }
Your existing HTML dependency is good to keep:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
内容的提问来源于stack exchange,提问作者Kees de Jager

