含度数符号的字符串截取:无法定位°符号的解决方案咨询
解决纬度字符串中度数符号定位问题
问题根源
你遇到的情况是因为字符串中的"°"并非标准的Unicode字符U+00B0(度数符号),而是视觉相似的其他字符(比如U+00BA masculine ordinal indicator、U+2103摄氏度符号,或是全角符号),导致直接匹配"°"或"\u00b0"失效。
解决方法
1. 确认符号的真实Unicode码点
先遍历字符串,输出每个字符的Unicode码点,明确目标符号的真实编码:
const latStr = "57°46'52\"W"; for (let i = 0; i < latStr.length; i++) { console.log(`位置${i}的字符: ${latStr[i]},码点: ${latStr.charCodeAt(i).toString(16)}`); }
拿到码点后,就可以直接用对应的Unicode转义符(比如\u00ba)来定位或替换。
2. 用正则直接提取度数(推荐)
不需要依赖具体符号,直接匹配字符串开头1-3位数字,适配度数的格式要求:
const latStr = "57°46'52\"W"; const degreeMatch = latStr.match(/^(\d{1,3})/); if (degreeMatch) { const degrees = degreeMatch[1]; console.log(`提取的度数:${degrees}`); // 输出 57 }
3. 匹配所有可能的角度相关符号
如果需要定位符号位置,可以把常见的视觉相似符号都纳入匹配范围:
const latStr = "57°46'52\"W"; const degreeSymbolRegex = /[°º˚℃℉]/; // 包含常见的角度/温度类相似符号 const symbolIndex = latStr.search(degreeSymbolRegex); if (symbolIndex !== -1) { const degrees = latStr.slice(0, symbolIndex); console.log(`提取的度数:${degrees}`); // 输出 57 }
内容的提问来源于stack exchange,提问作者Andrew L
相关产品推荐
相关产品推荐

